require "Common/define"
require "Logic/Config"
require "Common/functions"
require "Net/RankBattleHandler"
require "Battle/Editor/SkillRoleMgr"

local TopPanel = require "View/BattleUI/UIBattleTopChapterPanel"
---@type BattleTeamDarkStreetPanel
local BattleTeamDarkStreetPanel = require("View/BattleUI/BattleTeam/BattleTeamDarkStreetPanel")
local type = type
--- 支援队友站位
local SUPPORT_TEAMMATE_SITE = 6

UIBattleTeamEditor = UIBase.New(PanelNames.UIBattleTeamEditor)
local fightType = nil
local param = nil
local battleAct = nil
local backAct = nil
local currentFightType = -1
local nodeCount = 5
local mapName = ""
local m_team_list --预设编队列表
local m_choose_team --当前选择的编队

--fightType 战斗类型
--param  参数 （用来处理特殊要求,比如竞技场 进攻/防守 和对手阵容）
--battleAct  必填
--backAct 可空
function UIBattleTeamEditor.Init(_fightType, _param, _battleAct, _backAct)
    --AudioManager.PlayByEventName("Set_SubMenu_Battle_State_None",nil,AudioManager.WwiseFlagEnum.Music)
    fightType = _fightType
    param = _param;
    battleAct = _battleAct;
    backAct = _backAct;
    -- BattlePlaybackManager.SetFightType(_fightType)

    UIBattleTeamEditor.fairyBatching = false
    UIBase.Init(UIBattleTeamEditor, backAct)

end
function getPartnerById(id)
    for i = 1, #self.tableHeros do
        if self.tableHeros[i].partnerId == id then
            return self.tableHeros[i]
        end
    end
end

function UIBattleTeamEditor:OnCreate(obj)

    self.isInit = true
    self._restrainTime = 2000 -- 对位克制箭头消失时间(毫秒)
    self.powerEnemyNum = 0
    self.formationType = nil
    self.tabBtnHeroType = {}
    self.dynamicList = nil
    self.btnBack = nil
    self.btnBoss = nil
    self.resetHeroBtn = nil
    self.teamController = nil
    self.tableFormationIndex = {}--编队按钮
    self.isShowTitle = false
    self.isShowDebris = false--显示碎片

    self.petShowCfg = {}

    self.curTabType = nil
    self.tabHeroItem = {}
    self.isNeedOpenHeadMenu = false
    self.tabHeroPosItem = {}
    self.selectedDrag = nil
    self.startPos = nil
    self.dragPos = nil
    self.tileWidth = 100
    self.tileHeight = 200
    self.curHeroData = nil
    self.tabHeroPosDataTemp = {}
    self.tabHeroPosDataTemp2 = {}
    self.tabHeroPosData = {}
    self.tabMonsterPosData = {}
    self.helpMan = {};
    self.helpManId = {};
    self.enemyHelpMan = {}
    self.enemyHelpManId = { 0, 0, 0 }
    self.tabOwner = {}
    self.tableHeros = {} -- 可选的英雄列表
    self.formations = {} -- 阵容列表 key:阵容索引 value:id数组
    self.oppoFormations = {} -- 敌方阵容列表 key:阵容索引 value：partnerId,parnterMdoelId,level,star
    self.formationsIndex = nil --当前设置的第几阵容
    self.formationsMax = 1 --本次阵容设置数量
    self.battleBossFunction = nil --点击战斗的回调函数 参数：self.formations 无返回值
    self.backFunction = nil -- 返回的回调函数 无参无返回值
    self.checkFunction = nil -- 阵容设置结束后判断是否可以通过 参数：阵容列表 返回bool
    self.Count = 0
    self.oderLayer = nil
    self.enemyIndex = { 1, 3, 2, 4, 5 }
    self._counterpointList = { 1, 2, 1, 2, 2 } -- 对位关系
    self.restrainObjList = { {}, {} }
    self.playRestrainTimeList = { {}, {} }
    self.stageConfig = nil
    self.curFightType = nil
    self.leftPos = {}
    self.leftIndex = {}
    self.leftRole = {}
    self.rightPos = {}
    self.leftRect = {}
    self.leftRectPos = {}
    self.occupationBtns = {}
    self.occupationItems = {}--职业图片
    self.occupationEnemyItems = {}--敌人职业图片
    self.heroRectItems = {}
    self.battleInfo = {}
    self.battleInfo.myHelpManId = {}
    self.battleInfo.enemyHelpManId = {}
    self.battleInfo.helpSkillId = 0
    self.clickIndex = 0
    self.isFriendBattle = nil
    self.playerIds = {}
    self.btnShowDec = nil

    self.leftBottoms = {}
    self.rightBottoms = {}
    self.allHpText = nil
    self.allAttackText = nil
    self.tipsText = nil--提示信息
    self.effectList = {}
    self.effectTimers = {}
    self.isMove = false;
    self.btnChapterReward = nil;
    self.btnChapterRewardTips = nil;
    self.btnChapterRewardIcon = nil;
    self.combinationList = nil;--羁绊技能列表
    self.combinationListEnemy = nil;--敌人羁绊列表
    self.combinationListEnemyBgCtrl = nil;--敌人羁绊列表背景
    self.combinationListBgCtrl = nil;--我方羁绊列表背景
    self.combinationCom = nil;--羁绊技能
    self.btnCombinationComClose = nil;--关闭羁绊界面
    self.combinationComCtrl = nil;--显示羁绊技能
    self.combinationListInfo = {};--羁绊技能数据
    self.combinationListInfoEnemy = {};--敌人羁绊技能数据

    for i = 1, 6 do
        local item = self:GetChild("occupation_" .. i)
        table.insert(self.occupationBtns, item)
    end
    for i = 1, 8 do
        local role = self:GetChild("leftRect" .. i)
        table.insert(self.leftRect, role)
    end
    for i = 1, 8 do
        local role = self:GetChild("left" .. i);
        role.displayObject.gameObject.name = "left" .. i
        role.draggable = true;
        role.onTouchBegin:Add(function()
            self.isMove = true;
            self:onDragStartFunc(role)
        end);
        role.onTouchMove:Add(function()
            self:onDragMoveFunc(role)
        end);
        role.onTouchEnd:Add(function()
            self:onDragEndFunc(role)
            self.isMove = false;

        end);
        table.insert(self.leftRole, role);
        role.onClick:Add(function()
            if self.clearController.selectedIndex == 1 then
                return
            end
            if i >= nodeCount + 1 then
                if fightType == EnumConst.FightTypeConst.RankBattle and logicMgr.RankBattleManager.BanPick() then
                    if logicMgr.RankBattleManager.LastIsChoose(self.helpMan[self.formationsIndex].partnerModelId) then
                        return
                    end
                end
                if self.playerIds[i] and int64ToNumber(self.playerIds[i]) ~= 0 then
                    self:BorrowInfo(self.helpMan[self.formationsIndex])
                else
                    self:onClickHero(self.helpMan[self.formationsIndex], self.tabHeroItem[tostring(self.helpManId[self.formationsIndex])]);
                end
            else
                if fightType == EnumConst.FightTypeConst.RankBattle and logicMgr.RankBattleManager.BanPick() then
                    if logicMgr.RankBattleManager.LastIsChoose(self.tabHeroPosData[i].partnerModelId) then
                        return
                    end
                end
                if self.tabHeroPosData[i]["partnerId"] ~= nil then
                    if self.playerIds[i] and int64ToNumber(self.playerIds[i]) ~= 0 then
                        self:BorrowInfo(self.tabHeroPosData[i])
                    else
                        self:onClickHero(self.tabHeroPosData[i], self.tabHeroItem[self.tabHeroPosData[i]["partnerId"]])
                    end
                end
            end
        end)
        table.insert(self.leftIndex, role.parent:GetChildIndex(role))
    end
    for i = 1, 8 do
        local role = self:GetChild("right" .. i)
        role.displayObject.gameObject.name = "right" .. i
        table.insert(self.rightPos, role)
    end
    for i = 1, 8 do
        local leftBottom = self:GetChild("Loader_Left" .. i)
        local rightBottom = self:GetChild("Loader_Right" .. i)

        table.insert(self.leftBottoms, leftBottom)
        table.insert(self.rightBottoms, rightBottom)
    end
    for i = 1, #self._counterpointList do
        table.insert(self.restrainObjList[1], self:GetChild("myteam" .. i))
        table.insert(self.restrainObjList[2], self:GetChild("enemyteam" .. i))
    end

    self.leftGroup = self:GetChild("groupLeft")
    self.btnController = self:GetController("btnController")
    self.power = self:GetChild("power")
    self.bg = self:GetChild("bg")
    self.powerEnemy = self:GetChild("powerEnemy")
    self.helpSkill = self:GetChild("Icon")
    self.enemyHelpSkill = self:GetChild("Icon2")
    self.supSkillLeftBtn = self:GetChild("LeftSup")
    self.skillRedDots = self:GetChild("SkillRedDots")
    self.petSkillLeftBtn = self:GetChild("PetSup")
    self.petskillRedDots = self:GetChild("PetSup/n11")
    local Com_EnemySup = self:GetChild("Com_EnemySup")
    self.supSkillRight = Com_EnemySup:GetChild("RightSup")
    self.dynamicList = self:GetChild("headList")
    self.btnBack = self:GetChild("BtnBack")
    self.btnBoss = self:GetChild("BtnBoss")
    self.btnManual = self:GetChild("Manual")
    self.btnQuickChange = self:GetChild("btn_quickchange");
    self.resetHeroBtn = self:GetChild("n50")
    self.teamController = self:GetController("team")
    self.btnShowDec = self:GetChild("showDec")
    self.text_clearRequist = self:GetChild("text_clearRequist")
    self.btnShowDebris = self:GetChild("showDebris")    --奇异碎片
    self.btnPetShow = self:GetChild("showInfo")
    --self.titleNode = self:GetChild("teamTitleNode")
    self.ctrlIfMainBattle = self:GetController("ifMainBattle")
    self.friendCtrl = self:GetController("friendctrl")
    self.myWinTimerText = self:GetChild("winMy")
    self.otherWinTimerText = self:GetChild("winOther")
    self.competeBattleWinsCtrl = self:GetController("CompeteBattleWins")
    --self.bgCtrl = self:GetController("BgFront")
    self.supCtrl = self:GetController("Sup")
    self.tipsText = self:GetChild("Text_ClickHeroTips")
    self.ctrlNumTeams = self:GetController("NumTeams")
    self.clearController = self:GetController("Clear")

    self.btn_close = self:GetChild("btnClose")
    self.btn_bgclose = self:GetChild("bgclose")
     
    self.showHeroEffects = { {}, {} }
    for i = 1, 8 do
        local itemLeft = self:GetChild("Effect_Left" .. i)
        local itemRight = self:GetChild("Effect_Right" .. i)
        table.insert(self.showHeroEffects[1], itemLeft)
        table.insert(self.showHeroEffects[2], itemRight)

    end
    for i = 1, 5 do
        local btn = self:GetChild("team" .. i)
        btn.visible = false;
        table.insert(self.tableFormationIndex, btn)
    end

    self.btnChapterReward = self:GetChild("btnChapterReward");
    self.btnChapterRewardTips = self.btnChapterReward:GetChild("tips");
    self.btnChapterRewardIcon = self.btnChapterReward:GetChild("icon");
    local btnChapterRewardTitle = self.btnChapterReward:GetChild("title");
    btnChapterRewardTitle.text = getLanguage("ChapterRewardText2");

    self:addEvent();
    if not self.topChapterPanel then
        self.topChapterPanel = TopPanel.New()
        self.topChapterPanel:OnCreate(self:GetChild("txtCom"))
        self.topChapterPanel:InitMiniMap(self:GetChild("MapBtn"))
    end
    self.darkStreetPanel = BattleTeamDarkStreetPanel.New()
    local Com_Now = self:GetChild("Com_Now")
    local Com_Next = self:GetChild("Com_Next")
    local Text_RewardLimit = self:GetChild("Text_RewardLimit")
    local Text_RewardLimit2 = self:GetChild("Text_RewardLimit2")
    local ctrlDarkStreetNext = self:GetController("DarkStreet")
    self.darkStreetPanel:OnCreate(Com_Now, Com_Next, Text_RewardLimit, Text_RewardLimit2, ctrlDarkStreetNext)
    self.combinationCom = self:GetChild("HeroComb");
    self.btnCombinationComClose = self:GetChild("n622");
    self.combinationList = self:GetChild("CombinationList");
    self.combinationList.itemRenderer = function(idx, obj)
        self:rendererCombinationSkillItem(idx, obj, self.combinationListInfo, 0);
    end
    self.combinationListBgCtrl = self:GetController("Combination");--敌人羁绊列表
    self.combinationListEnemyBgCtrl = self:GetController("CombinationEnemy");--敌人羁绊列表背景
    self.combinationListEnemy = self:GetChild("CombinationList_Enemy");
    self.combinationListEnemy.itemRenderer = function(idx, obj)
        self:rendererCombinationSkillItem(idx, obj, self.combinationListInfoEnemy, 1);
    end
    self.combinationComCtrl = self:GetController("showComb");
    self.mapHolder = self:GetChild("Graph_AutoFightMap");
    self:SetBgType()

    BattlePlaybackManager.isWaiting = false
end

function UIBattleTeamEditor:refresh()
    for i = 1, #self._counterpointList do
        self.restrainObjList[1][i].visible = false
        self.restrainObjList[2][i].visible = false
    end
    self.tipsText.text = self.isShowTitle and getLanguage("BattleTeamTips2") or getLanguage("BattleTeamTips1")
    self.text_clearRequist.text = string.format(getLanguage("TeamsTips001"), self.formationsMax)
    self.btnManual.visible = false
    if logicMgr.FuncOpenManager.isOpen(208) then
        self.btnManual.visible = true
    end
    if fightType == EnumConst.FightTypeConst.DUNGEON and next(logicMgr.BattlePlaybackManager.GetGroupBossHistory()) ~= nil then
        self.tipsText.text = "该场战斗已经打响，不能进行英雄养成"
    elseif fightType == EnumConst.FightTypeConst.GuildBattlePlus then
        self.tipsText.text = ""
    end
    local help_pos_idx = nodeCount + 1
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, false) then
        self.leftRect[help_pos_idx].visible = true
        self.leftRole[help_pos_idx].visible = true
        self.rightPos[help_pos_idx].visible = true
    else
        self.leftRect[help_pos_idx].visible = false
        self.leftRole[help_pos_idx].visible = false
        self.rightPos[help_pos_idx].visible = false
    end
    for j = 1, self.formationsMax do
        for i = 1, nodeCount do
            self.tabHeroPosDataTemp[j][i] = {}

        end
        self.helpMan[j] = {}
    end
    self.tabHeroPosData = {}
    self:GetController("teamId"):SetSelectedIndex(0)
    if self.teamController.selectedIndex ~= 0 then
        self.teamController:SetSelectedIndex(0)
    end
    self:onClickType()

    if self.formationsMax > 1 then
        for i = 1, self.formationsMax do
            local go = self.tableFormationIndex[i]
            go.visible = true
            go.onClick:Clear()
            go.onClick:Add(function()
                self:onClickItemIndex(i)
            end);
            go:GetController("Clear").selectedIndex = 0;
            if fightType == EnumConst.FightTypeConst.DUNGEON then
                local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory(i)
                if data and data.record and data.record.win == 1 then
                    go:GetController("Clear"):SetSelectedIndex(1)
                end
            elseif fightType == EnumConst.FightTypeConst.GuildBattlePlus then
                if param.formationIsOver and param.formationIsOver[i] then
                    go:GetController("Clear"):SetSelectedIndex(1)
                end
            end
        end
    end

    for i = self.formationsMax + 1, #self.tableFormationIndex do
        self.tableFormationIndex[i].onClick:Clear();
        self.tableFormationIndex[i].visible = false;
    end

    self:RefreshBossBtn()
    self:initBg()
    if fightType == EnumConst.FightTypeConst.DUNGEON then
        if self.formationsMax > 1 then
            self.ctrlIfMainBattle:SetSelectedIndex(4)
        else
            self.ctrlIfMainBattle:SetSelectedIndex(1)
        end
        self.topChapterPanel:Refresh()
        self:RefreshChapterRewardBtn();
    elseif fightType == EnumConst.FightTypeConst.RankBattle then
        self.ctrlIfMainBattle:SetSelectedIndex(2)
    elseif fightType == EnumConst.FightTypeConst.DarkStreet then
        self.ctrlIfMainBattle:SetSelectedIndex(3)
        self.darkStreetPanel:Refresh()
    else
        self.ctrlIfMainBattle:SetSelectedIndex(0)
    end
    --[[if fightType == EnumConst.FightTypeConst.ARENA then
        if self.formationType == 3 or self.formationType == 4 then
            self.ctrlIfMainBattle:SetSelectedIndex( 5 )
        end
    end--]]
    self:initFormation()
    self:rendererFormation()
    self:initEnemyFormation()
    if self.isInit then
        self.isInit = false
    end
    self:refreshCombinationSkill();

end
--拖动开始
function UIBattleTeamEditor:onDragStartFunc(item)
    if self.clearController.selectedIndex ~= 0 then
        item.draggable = false;
        return ;
    end
    item.draggable = true
    if fightType == EnumConst.FightTypeConst.RankBattle and logicMgr.RankBattleManager.BanPick() then
        if logicMgr.RankBattleManager.LastIsChoose(item.data.partnerModelId) then
            item.draggable = false
            return
        else
            item.draggable = true
        end
    else
        item.draggable = true
    end
    if item.draggable and item.data.state ~= 0 and item.data.state ~= nil then
        AudioManager.Play(1031)
        --item.parent:SetChildIndex(item, item.parent:GetChildIndex(self.titleNode) - 1)
        local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem)
        local type = self.isShowTitle and 1 or 0
        ctrlItem.updateTitle(item:GetChild("title"), item.data, type, item.data.teamIdx, fightType, self.formationType)

        item:GetChild("title").visible = true
        --local titleItem = logicMgr.UIShowManager.getTeamHeroItem(item.data.teamIndex, item.data.teamIdx)
        --titleItem.visible = false
    end
end

function UIBattleTeamEditor:onDragMoveFunc(item)
    if self.isMove == false then
        return ;
    end
    local index = 0;
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    --ctrlItem.updateTitlePos(item, item.data, item.data.teamIdx);
    for i = 1, nodeCount + 1 do
        if self.leftRole[i] == item then
            index = i;
            break ;
        end
    end
    local inPos = 0;
    for i = 1, nodeCount + 1 do
        if isIntersect(self.leftRect[i], item) == true then
            inPos = i;
            break
        end
    end

    for i = 1, nodeCount + 1 do
        if (index ~= i) then
            self.leftRole[i]:SetPosition(self.leftRect[i].x, self.leftRect[i].y, 0);
            ctrlItem.updateTitlePos(self.leftRole[i], self.leftRole[i].data, self.leftRole[i].data.teamIdx, fightType, nodeCount + 1);

        end
    end
    if (inPos ~= 0) then
        if (inPos ~= index) then
            self.leftRole[inPos]:SetPosition(self.leftRect[index].x, self.leftRect[index].y, 0);
            ctrlItem.updateTitlePos(self.leftRole[inPos], self.leftRole[inPos].data, self.leftRole[inPos].data.teamIdx, fightType, nodeCount + 1);
        end
    end

end
function UIBattleTeamEditor:onDragEndFunc(item)
    if self.isMove == true then
        self.isMove = false;
    end
    item:GetChild("title").visible = false;
    --logicMgr.UIShowManager.getTeamHeroItem(item.data.teamIndex, item.data.teamIdx).visible = true;
    AudioManager.Play(1032)

    local index = 0;
    for i = 1, nodeCount + 1 do
        if self.leftRole[i] == item then
            index = i;
            break ;
        end
    end
    local inPos = 0;
    for i = 1, nodeCount + 1 do
        if isIntersect(self.leftRect[i], item) == true then
            inPos = i;
            break
        end
    end
    if (inPos ~= 0) then
        if fightType == EnumConst.FightTypeConst.RankBattle and logicMgr.RankBattleManager.BanPick() then
            if logicMgr.RankBattleManager.LastIsChoose(item.data.partnerModelId) then
                return
            end
            local modelId
            if inPos > nodeCount then
                modelId = self.helpManId[self.formationsIndex]
            else
                modelId = self.tabHeroPosData[inPos].partnerModelId
            end
        end
        self:changePosByIndex(index, inPos);
    else
        self:changePosByIndex(index, index)
    end
    item:SetPosition(self.leftRect[index].x, self.leftRect[index].y, 0);
    if (index ~= 0) then
        item.parent:SetChildIndex(item, self.leftIndex[index]);
    end
end

function UIBattleTeamEditor:addEvent()
    self.resetHeroBtn.onClick:Add(function()
        if currentFightType == EnumConst.FightTypeConst.DUNGEON then
            TAManager.TrackByDictionary("ui_battle_team_reset")
        end
        for i = 1, nodeCount + 1 do
            if i >= nodeCount + 1 then
                if self.playerIds[i] and tostring(self.playerIds[i]) ~= "0" then
                    self:BorrowInfo(self.tabHeroPosData[i])
                else
                    if fightType == EnumConst.FightTypeConst.RankBattle then
                        self:onClickHero(self.helpMan[self.formationsIndex], self.tabHeroItem[tonumber(tostring(self.helpManId[self.formationsIndex]))]);
                    else
                        self:onClickHero(self.helpMan[self.formationsIndex], self.tabHeroItem[tostring(self.helpManId[self.formationsIndex])]);
                    end
                end
            else
                if self.tabHeroPosData[i] and self.tabHeroPosData[i]["partnerId"] then
                    if self.playerIds[i] and tostring(self.playerIds[i]) ~= "0" then
                        self:BorrowInfo(self.tabHeroPosData[i])
                    else
                        self:onClickHero(self.tabHeroPosData[i], self.tabHeroItem[self.tabHeroPosData[i]["partnerId"]]);
                    end
                end
            end
        end
    end)
    self:RegisterOnClick(self.btnShowDec, self.changeHeroItemTitle);
    self:RegisterOnClick(self.BtnGo, self.onClick_gotoHeroMain)
    self:RegisterOnClick(self.btnChapterReward, self.onClickChapterReward);
    self:RegisterOnClick(self.btnShowDebris, self.changeShowDebris);
    self:RegisterOnClick(self.supSkillLeftBtn, function()
        self:onOpenSupSkillSelect(0)
    end );
    self:RegisterOnClick(self.petSkillLeftBtn, function()
        self:onOpenSupSkillSelect(1)
    end );
    self:RegisterOnClick(self.btn_teamEditor, self.onClickTeamEditor)
    self:RegisterOnClick(self.btnBack, self.onClickBack1);
    self:RegisterOnClick(self.btnBoss, self.onClickBoss);
    self:RegisterOnClick(self.btnManual, self.onClickManual);
    self:RegisterOnClick(self.Btn_Add, self.OnClickChallengeBtnAdd)
    self:RegisterOnClick(self.btn_close, self.onClick_CloseTeamEditor)
    self:RegisterOnClick(self.btn_bgclose, self.onClick_CloseTeamEditor)
    self:RegisterOnClick(self.btnPetShow, function()
        local paramTeamBonus = {}
        paramTeamBonus.tabHeroPosData = self.tabHeroPosData;
        paramTeamBonus.formationsIndex = self.formationsIndex;
        paramTeamBonus.helpMan = self.helpMan;
        showUI(PanelNames.UITeamBonus, paramTeamBonus);
    end)
    self:RegisterOnClick(self:GetChild("Tips"), function()
        showUI(PanelNames.UITeamBonus);
    end)
    self:RegisterOnClick(self:GetChild("Img_Lock3"), function()
        logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, true, self:GetChild("Img_Lock3"))
    end)
    self:RegisterOnClick(self:GetChild("Img_Lock4"), function()
        logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, true, self:GetChild("Img_Lock4"))
    end)
end

function UIBattleTeamEditor:LocalListenEvent()
    self:GetController("team").onChanged:Add(function()
        self:onClickType()
    end);
    self:RegisterEvent(Config.EventType.AssistantSkill, self.refreshSupSkill);
    -- self:RegisterEvent(Config.EventType.BorrowFriendHero, self.BorrowInfo);
    -- self:RegisterEvent(Config.EventType.GuideTeamRoleTouch, self.GuideTeamRoleTouch)
    -- self:RegisterEvent(Config.EventType.GuideFindHeroId, self.GuideFindHeroIdMsg)
    -- self:RegisterEvent(Config.EventType.TouchAnyKey, self.TouchAnyKeyMsg)
    -- self:RegisterEvent(Config.EventType.SetDefFormation, function()
    --     self:setSelfFormationByType(fightType, param);
    --     self:refresh()
    -- end)
    -- self:RegisterEvent(Config.EventType.BtnFriendCtr, function(self, msg)
    --     self.friendCtrl:SetSelectedIndex(msg[1])
    --     self.teamController:SetSelectedIndex(0)
    -- end)
    -- self:RegisterEvent(Config.EventType.RankBattleTeam, self.RankBattleTeam)
    -- self:RegisterEvent(Config.EventType.RankBattleEnemylock, self.BPformation)
    -- self:RegisterEvent(Config.EventType.BPReConnect, self.BPformation)
end

function UIBattleTeamEditor:LocalCloseEvent()
    self:UnRegisterEvent(Config.EventType.AssistantSkill, self.refreshSupSkill);
    -- self:UnRegisterEvent(Config.EventType.BorrowFriendHero, self.BorrowInfo);
    -- self:UnRegisterEvent(Config.EventType.GuideTeamRoleTouch, self.GuideTeamRoleTouch)
    -- self:UnRegisterEvent(Config.EventType.GuideFindHeroId, self.GuideFindHeroIdMsg)
    -- self:GetController("team").onChanged:Clear();
end

function UIBattleTeamEditor:BPformation(msg)
    if logicMgr.RankBattleManager.BanPick() then
        self:setOppoFormationByType(fightType, param)
        self:initEnemyFormation()
        self.dynamicList.numItems = #self.tabOwner
    end
    if msg then
        self:setSelfFormationByType(fightType, msg)
        self:initFormation()
        self:rendererFormation()
    end
end

function UIBattleTeamEditor:RankBattleTeam(fun, isFire)
    local info = { 0, 0, 0, 0, 0, 0 }
    local flag = false;
    for k, v in ipairs(self.tabHeroPosData) do
        if v.partnerModelId then
            info[k] = v.partnerModelId
            flag = true;
        end
    end
    local helpId = self.helpMan[self.formationsIndex]["partnerModelId"]
    if helpId then
        info[6] = helpId
        flag = true;
    end
    if isFire then
        if not logicMgr.RankBattleManager.BanPick() then
            RankBattleHandler.ReqRankBattleLock(info, self.battleInfo.helpSkillId)
        else
            local myformation = logicMgr.RankBattleManager.GetBPFormation()
            for k, v in ipairs(myformation) do
                if v and v ~= 0 then
                    info[k] = 0
                end
            end
            local bpinfo = {}
            for k, v in ipairs(info) do
                if v and v ~= 0 then
                    local item = HeroSite.New();
                    item.heroId = v
                    item.site = k
                    table.insert(bpinfo, item)
                end
            end
            RankBattleHandler.BPReqRankBattleLock(bpinfo)
        end
        return
    end
    if flag then
        if not logicMgr.RankBattleManager.BanPick() then
            RankBattleHandler.ReqRankBattleLock(info, self.battleInfo.helpSkillId)
        else
            local myformation = logicMgr.RankBattleManager.GetBPFormation()
            for k, v in ipairs(myformation) do
                if v and v ~= 0 then
                    info[k] = 0
                end
            end
            local bpinfo = {}
            for k, v in ipairs(info) do
                if v and v ~= 0 then
                    local item = HeroSite.New();
                    item.heroId = v
                    item.site = k
                    table.insert(bpinfo, item)
                end
            end
            RankBattleHandler.BPReqRankBattleLock(bpinfo)
        end
    else
        UISysTips.AddMsg(getLanguage("ErrorCode_3404"))
        return
    end
    if fun then
        fun(flag);
    end
end

function UIBattleTeamEditor:OnDestroy()
    if not HelperFunc.IsNull(self.battleMapGo) then
        Util.Lua_SetLocalPositionXYZ(self.battleMapGo, self.originalPos.x, self.originalPos.y, self.originalPos.z);
        Util.Lua_SetLocalScaleXYZ(self.battleMapGo, self.originalScale.x, self.originalScale.y, self.originalScale.z);
        Util.Lua_SetLocalRotationXYZ(self.battleMapGo, self.originalRotation.x, self.originalRotation.y, self.originalRotation.z);
        self.battleMapGo.gameObject:SetActive(false);
        Util.SetLayerMask(self.battleMapGo.gameObject, "Default", true);
    end
    for k, v in pairs(self.leftRole) do
        v.onClick:Clear();
    end
    if self.topChapterPanel then
        self.topChapterPanel:OnDestroy()
    end
    if self.timerId then
        utimer.remove(self.timerId)
        self.timerId = nil
    end
    self.topChapterPanel = nil
    self:RemoveEffect()
    if self.darkStreetPanel then
        self.darkStreetPanel:OnDestroy()
    end
    self.darkStreetPanel = nil
    
    --self.darkStreetTimerId = nil

    if self.goWrapper then
        self.goWrapper:Dispose()
        self.goWrapper = nil
    end
    if self.mapObj then
        Util.Lua_SetLocalPositionXYZ(self.mapObj.transform, 0, 1000, 0);
        destroy(self.mapObj);
        self.mapObj = nil
        mapName = ""
        --self.mapObj.gameObject:SetActive(false)
    end
    --
    --if self.teamHeroItemList then
    --    for key, value in pairs(self.teamHeroItemList) do
    --        value:Destroy()
    --    end
    --    self.teamHeroItemList = nil
    --end
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    ctrlItem.onClear();
    ctrlItem.Destroy();

    local ctrlItem = CtrlManager.GetCtrl(PanelNames.UIBattleTeam);
    if ctrlItem and isOpenUI(PanelNames.UIBattleTeam) then
        ctrlItem:refresh()
    end

    self:LocalCloseEvent()
end

function UIBattleTeamEditor:changeShowDebris()
    self.isShowDebris = not self.isShowDebris;
    if self.isShowDebris then
        UISysTips.AddMsg(getLanguage("DebrisCheckTips1"));
    else
        UISysTips.AddMsg(getLanguage("DebrisCheckTips2"));

    end
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    for i = 1, #self.tabHeroPosData do
        if nodeCount >= i then
            local role = self.leftRole[i];
            local itemData = self.tabHeroPosData[i];
            if ctrlItem ~= nil then
                ctrlItem.updateDebris(role, itemData, self.isShowDebris);
            end
        end
    end
    local role = self.leftRole[nodeCount + 1];
    local itemData = self.helpMan[self.formationsIndex];
    if ctrlItem ~= nil then
        --初始装备信息
        ctrlItem.updateDebris(role, itemData, self.isShowDebris);
    end

    self:onClickType();
end

function UIBattleTeamEditor:onClick_gotoHeroMain()
    self:onClickBack();
    UIBottom.enterPlayer()
end

function UIBattleTeamEditor:changeHeroItemTitle()
    if currentFightType == EnumConst.FightTypeConst.DUNGEON then
        TAManager.TrackByDictionary("ui_battle_team_change_info")
    end
    --self.pageTips:GetController("TipsShow").selectedIndex = 0;
    self.isShowTitle = not self.isShowTitle;
    self.tipsText.text = self.isShowTitle and getLanguage("BattleTeamTips2") or getLanguage("BattleTeamTips1");
    if fightType == EnumConst.FightTypeConst.DUNGEON and next(logicMgr.BattlePlaybackManager.GetGroupBossHistory()) ~= nil then
        self.tipsText.text = "该场战斗已经打响，不能进行英雄养成";
    end
    logicMgr.FriendBattleManager.ShowTitle(self.isShowTitle)
    local type = self.isShowTitle and 1 or 0;
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    for i = 1, #self.tabHeroPosData do
        if nodeCount >= i then
            local itemData = self.tabHeroPosData[i];
            if ctrlItem ~= nil then
                ctrlItem.updateTitle(nil, itemData, type, i, fightType, self.formationType);
            end
        end
    end
    local itemData = self.helpMan[self.formationsIndex];
    if ctrlItem ~= nil then
        --初始装备信息
        ctrlItem.updateTitle(nil, itemData, type, nodeCount + 1, fightType, self.formationType);
    end
    self:initEnemyFormation()
    self:onClickType();
    FireEvent(Config.EventType.FriendBorrowHeroList)
end

function UIBattleTeamEditor:OnEnable()
    self.friendCtrl.selectedIndex = 0
    self.competeBattleWinsCtrl.selectedIndex = 0;
    self.fguiObj.fairyBatching = true;
    self.isClickBattle = false
    self.isShowTitle = false;
    self.isShowDebris = false;
    
    self.btnShowDebris.visible = false;
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattleTeamEditor, Config.FuncOpenType.SupSkill, self.supSkillLeftBtn.name, self.supSkillLeftBtn);
    --logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIBattleTeamEditor, Config.FuncOpenType.PetPartAttr, self.supSkillLeftBtn.name.."pet", self.petSkillLeftBtn);
    FuncOpenManager.addStatusCtr(PanelNames.UIBattleTeamEditor, Config.FuncOpenType.SupSkill, self.supSkillRight.name, self.supSkillRight);
    FuncOpenManager.addStatusCtr(PanelNames.UIBattleTeamEditor, Config.FuncOpenType.BattleTeamPet, self.btnPetShow.name, self.btnPetShow);

    self.helpMan = { {}, {}, {} };
    self.helpManId = {};
    self.enemyHelpMan = { {}, {}, {} };
    self.enemyHelpManId = { 0, 0, 0 };

    if self.stageConfig == nil then
        self.stageConfig = G.dataTable["t_stage"];
    end
    
    self.tableHeros = logicMgr.HeroManager.getOwnerHeroList(false)
    --logicMgr.HeroManager.SetMyHeroSkin(self.tableHeros)
    table.sort(self.tableHeros, self.sortHero);
    for i = 1, #self.tableHeros do
        --logicMgr.HeroManager.setHeroState(self.tableHeros[i].partnerId, false, EnumConst.HeroHeadStateEnum.BATTLE, fightType, self.tableHeros[i]);
        if logicMgr.StrangeFragmentManager.GetFragmentInfoByPartnerId(self.tableHeros[i].partnerId) and not self.btnShowDebris.visible then
            self.btnShowDebris.visible = true;
        end
        self.tableHeros[i]["state"] = 0
    end

    self.battleBossFunction = battleAct
    self.backFunction = backAct;
    self.curFightType = fightType;
    self.formationsIndex = 1
    self.formationsMax = 1
    
    self.ctrlNumTeams.selectedIndex = self.formationsMax > 1 and self.formationsIndex or 0
    self:EnableHeroTypeBtn();
    ----获取双方阵容数据
    self:setSelfFormationByType(fightType, param);
    self:setOppoFormationByType(fightType, param);
    self:refreshSupSkill();
    self:refresh()
    if self.formationType == EnumConst.FightTypeConst.FriendDefend or self.formationType == EnumConst.FightTypeConst.FriendAttack then
        self.isFriendBattle = true
        self.playerIds = logicMgr.FriendBattleManager.GetPlayerIds(self.formationType)
    else
        self.isFriendBattle = false
    end
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan) then
        self.supCtrl.selectedIndex = 0
    else
        self.supCtrl.selectedIndex = 1
    end
    
    self:LocalListenEvent();
end

function UIBattleTeamEditor:RefreshBossBtn()
    self.btnController:SetSelectedIndex(1)
end

function UIBattleTeamEditor:initBg()
    local mapId = logicMgr.MapManager.getMapId();
    --Util.SetPlayerPrefs("mapID", mapId);
    local current = self.stageConfig[tostring(mapId)];
    local bgId = current.f_MapType
    local mapIds = decodeJsonStrToTabel(G.dataTable["t_global"]["303"]["f_string_value"])
    for i = 1, #mapIds do
        if mapIds[i][1] == fightType then
            bgId = mapIds[i][2];
        end
    end
end

function UIBattleTeamEditor:onOpenSupSkillSelect(index)
    if index == 0 then
        if FuncOpenManager.isOpen(Config.FuncOpenType.SupSkill, true, self.supSkillLeftBtn) then
            showUI(PanelNames.UISupSelect, nil, fightType, self.formationType,index);
        end
    else
        if FuncOpenManager.isOpen(Config.FuncOpenType.PetPartAttr, true, self.petSkillLeftBtn) then
            showUI(PanelNames.UISupSelect, nil, fightType, self.formationType,index);
        end
    end
end

function UIBattleTeamEditor:refreshSupSkill()
    local self = UIBattleTeamEditor;
    local supSkills = logicMgr.SkillManager.getSupSkillInfo();
    if self.otherSupSkill then
        local skillDataOther = G.dataTable["t_skillshow"][tostring(self.otherSupSkill)];
        if skillDataOther then
            self.supSkillRight:GetChild("icon"):GetChild("icon").url = "ui://SkillAtlas/" .. skillDataOther.f_SkillIcon;
        end
    end
    --if #supSkills == 0 then
    --    self.skillRedDots.visible = false;
    --end
    local isRedDot = false;

    local index = FormationManager.GetFocus()
    local skill = FormationManager.GetTempSupskill(index)
    local petSkillId = FormationManager.GetTempPetskill(index)
    if skill ~= 0 then
        self.battleInfo.helpSkillId = tostring(skill)
        local skillData = G.dataTable["t_skillshow"][self.battleInfo.helpSkillId];
        self.supSkillLeftBtn:GetChild("icon"):GetChild("icon").url = "ui://SkillAtlas/" .. skillData.f_SkillIcon;
        self.skillRedDots.visible = false;
        isRedDot = false;
    else
        isRedDot = true;
    end
    self.petskillRedDots.visible = false
    if petSkillId ~= 0 then
        local petskillData = G.dataTable["t_skillshow"][tostring(petSkillId)];
        self.petSkillLeftBtn:GetChild("icon"):GetChild("icon").url = "ui://SkillAtlas/" .. petskillData.f_SkillIcon;
    else
        if FuncOpenManager.isOpen(Config.FuncOpenType.PetPartAttr) then
            self.petskillRedDots.visible = true
        end
    end
    -- if FormationManager.IsInEditor() then
        
    -- else
    --     for i = 1, #supSkills do
    --         if supSkills[i].skillId == SkillManager.getSupSkillIdByFormationType(self.formationType) then
    --             self.battleInfo.helpSkillId = tostring(supSkills[i].skillId);
    --             local skillData = G.dataTable["t_skillshow"][self.battleInfo.helpSkillId];
    --             if fightType == EnumConst.FightTypeConst.DUNGEON then
    --                 local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory(self.formationsIndex);
    --                 if data and data.record and data.record.win == 1 then
    --                     skillData = G.dataTable["t_skillshow"][tostring(data.record.supportSkill)];
    --                 end
    --             end
    --             self.supSkillLeftBtn:GetChild("icon"):GetChild("icon").url = "ui://SkillAtlas/" .. skillData.f_SkillIcon;
    --             self.skillRedDots.visible = false;
    --             isRedDot = false;
    --             break ;
    --         else
    --             isRedDot = true;
    --         end
    --     end
    -- end
    
    if not FuncOpenManager.isOpen(Config.FuncOpenType.SupSkill, false) then
        isRedDot = false;
    end
    self.skillRedDots.visible = isRedDot;
end

function UIBattleTeamEditor:OnDisable()
    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIBattleTeamEditor);

    -- if self.tableHeros then
    --     for i = 1, #self.tableHeros do
    --         logicMgr.HeroManager.setHeroState(self.tableHeros[i].partnerId, false, EnumConst.HeroHeadStateEnum.BATTLE, self.formationType, self.tableHeros[i]);
    --     end
    -- end
    self.isFriendBattle = nil
    self.playerIds = {}
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem);
    ctrlItem.onClear();
    ctrlItem.Destroy();
    self:LocalCloseEvent();

end

function UIBattleTeamEditor:onClickType()
    self.curTabType = self:GetController("team").selectedIndex;
    for k, v in pairs(self.occupationBtns) do
        local occupationType = tonumber(string.split(v.name, "_")[2]) or -1;
        if self.curTabType == occupationType and v.grayed then
            UISysTips.AddMsg(getLanguage("ClimbTowerTips6"));
            self.teamController.selectedIndex = self.curTabIndex;
            return ;
        end
    end
    self.curTabIndex = self.curTabType or 0;    --记录上一次点击的type
    if self.curTabType > 0 then
        logicMgr.FriendBattleManager.IsClickType(true)
    end
    for k, v in pairs(self.tabHeroItem) do
        v.onClick:Clear();
    end
    self.tabOwner = {};

    for i = 1, #self.tableHeros do
        if self.tableHeros[i].type == self.curTabType or EnumConst.HeroTypeEnum.HeroTypeAll == self.curTabType then
            if not self:isInFormations(self.tableHeros[i].partnerId, false) then
                -- local item = logicMgr.HeroManager.getHeroDatabyPartnerId(self.tableHeros[i].partnerId);
                table.insert(self.tabOwner, self.tableHeros[i]);
            end
        end
    end
    if self.formationType ~= EnumConst.FightTypeConst.RankBattle then
        local sortFun = HeroManager.getSortHeroByType()
        table.sort(self.tabOwner, sortFun);
    end

    self.Count = 0;
    self.index = 0;
    self.dynamicList.itemRenderer = function(index, obj)
        self:setData(index, obj);
    end
    self.dynamicList.numItems = #self.tabOwner;
    if self.curFightType == EnumConst.FightTypeConst.Expedition then
        self.dynamicList.lineGap = 30
    else
        self.dynamicList.lineGap = 5
    end
end

function UIBattleTeamEditor.sortHero(a, b)
    if a["level"] > b["level"] then
        return true;
    elseif a["level"] == b["level"] then
        if a["star"] > b["star"] then
            return true;
        elseif a["star"] == b["star"] then
            return a["partnerModelId"] < b["partnerModelId"];
        else
            return false;
        end
    else
        return false;
    end
end
---@param itemobj GComponent
function UIBattleTeamEditor:setData(index, itemobj)
    local self = UIBattleTeamEditor;
    --itemobj.visible = false
    --utimer.timeCall(function ()
    --itemobj.visible = true
    index = index + 1
    local itemValue = self.tabOwner[index];
    local go = itemobj;
    local type = self.isShowTitle and 1 or 0;
    itemobj:SetScale(1, 1)
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    --local ctrl = itemobj:GetTransition("Effect_List")
    --ctrl:Play()
    if charactor ~= nil then
        --初始英雄信息
        if itemValue then
            charactor.initData(go, itemValue, nil, fightType, nil, nil, nil, nil, nil, self.formationType);
            charactor.updateDecTitle(go, itemValue, type, nil, fightType, self.formationType);
            charactor.updateDebris(go, itemValue, self.isShowDebris, nil, fightType, self.formationType)
        end
    end
    self.Count = self.Count + 1;
    --go.onClick:Clear();
    --go.onClick:Add(function()
    --    HeroManager.HeroPlayCV(itemValue["partnerModelId"], EnumConst.HeroActionType.GoBattleTeame);
    --    self:onClickHero(itemValue, go);
    --end);
    go.onTouchBegin:Clear();
    go.onTouchEnd:Clear();
    --go.onTouchMove:Clear();
    go.onTouchBegin:Add(function(evt)
        self:OnTouchStart(evt, itemValue);
    end)
    go.onTouchMove:Add(function(evt)
        self:OnTouchMove(evt);
    end)
    go.onTouchEnd:Add(function()
        self:OnTouchUp(itemValue, go);
    end)
    go.displayObject.gameObject.name = "card" .. index;
    if itemValue then
        self.tabHeroItem[itemValue["partnerId"]] = go;
        if self.curFightType == EnumConst.FightTypeConst.Expedition then
            local expeditionInfo = logicMgr.ExpeditionMgr.GetHeroInfo(itemValue["partnerId"])
            if expeditionInfo then
                charactor.UpdateHPMPBar(itemobj, expeditionInfo.hp, expeditionInfo.energy)
            else
                charactor.UpdateHPMPBar(itemobj, 100, 100)
            end
        elseif self.curFightType == EnumConst.FightTypeConst.GuildBattlePlus and logicMgr.GuildBattlePlusManager.getNowType() == EnumConst.GuildBattlePlusType.Territory then
            charactor.UpdateCostPower(itemobj, logicMgr.GuildBattlePlusManager.getCostPowerMaxByType(), logicMgr.GuildBattlePlusManager.getCostPowerExpendByType(), logicMgr.GuildBattlePlusManager.getHeroPowerById(itemValue.partnerId))
        end
    end
    --end,100*index,1)
end

function UIBattleTeamEditor:OnTouchStart(evt, heroData)
    self.lastEventX = evt.inputEvent.x;
    self.lastEventY = evt.inputEvent.y;
    self.isTouching = true;
    self.timerId = utimer.timeCall(function()
        self.timerId = nil;
        if self.curFightType == EnumConst.FightTypeConst.GuildBattlePlus then
            return ;
        end
        local flag = true;
        for k, v in pairs(logicMgr.BattlePlaybackManager.GetGroupBossHistory()) do
            flag = false
        end
        -- if flag then
        --     if fightType ~= EnumConst.FightTypeConst.RankBattle then
        --         self.isNotNeedEnable = true;
        --         --self.fguiObj.visible = false;
        --         if self.isFriendBattle then
        --             closeUI(PanelNames.UITeam)
        --         end
        --         showUI(PanelNames.UICharactorInfoHero, heroData, nil, true, function()
        --             self:updateAllHeroData()
        --         end, nil, function()
        --             self:onClickBack1();
        --         end);
        --     end
        -- else
        --     UISysTips.AddMsg("该场战斗已经打响，不能进行英雄养成");
        -- end
    end, 500, 1);
end

function UIBattleTeamEditor:OnTouchMove(evt)
    if self.timerId ~= nil then
        if math.abs(self.lastEventY - evt.inputEvent.y) > 20 or math.abs(self.lastEventX - evt.inputEvent.x) > 20 then
            utimer.remove(self.timerId);
            self.timerId = nil;
            self.isTouching = false;
        end
    end
end

function UIBattleTeamEditor:OnTouchUp(itemValue, go)
    if self.timerId ~= nil and self.isTouching then
        utimer.remove(self.timerId);
        self.timerId = nil;
        if self.curFightType == EnumConst.FightTypeConst.GuildBattlePlus and logicMgr.GuildBattlePlusManager.getNowType() == EnumConst.GuildBattlePlusType.Territory then
            if logicMgr.GuildBattlePlusManager.getCostPowerExpendByType() > logicMgr.GuildBattlePlusManager.getHeroPowerById(itemValue.partnerId) then
                UISysTips.AddMsg("体力不足，无法上阵");
                return ;
            end
        end
        if self.clearController.selectedIndex == 0 then
            --上阵
            local battle = false
            for i = 1, nodeCount do
                if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i]["partnerId"] == itemValue.partnerId then
                    battle = true
                    break
                end
            end

            if not battle then
                --下阵不播
                AudioManager.PlayInteractionVoice(itemValue["partnerModelId"], 0, AudioManager.InteractionTagTable[16].Tag)
            end

            self:onClickHero(itemValue, go);
        end
    end
end

function UIBattleTeamEditor:updateAllHeroData()
    if HelperFunc.IsNull(self.fguiObj) then
        closeUI(PanelNames.UIBattleTeamEditor)
        return
    end
    --self.fguiObj.visible = true
    self.tableHeros = logicMgr.HeroManager.getOwnerHeroList(false);
    table.sort(self.tableHeros, self.sortHero)
    self:onClickType()
    self:initFormation()
    self:rendererFormation()
    self.isNotNeedEnable = false;
end

function UIBattleTeamEditor:onClickHero(heroData, go)
    local hero = heroData
    local data = heroData
    if hero ~= nil then
        if hero.state == EnumConst.HeroHeadStateEnum.BATTLE then
            for k,v in pairs(self.tabOwner) do
                if v.partnerId == heroData.partnerId then
                    v.state = 0
                end
            end
            
            if self.helpMan[self.formationsIndex] ~= nil and tostring(self.helpManId[self.formationsIndex]) == tostring(heroData["partnerId"]) then
                --data = logicMgr.HeroManager.setHeroState(heroData["partnerId"], false, EnumConst.HeroHeadStateEnum.BATTLE, self.formationType, hero);
                self.helpManId[self.formationsIndex] = "0"
                self.helpMan[self.formationsIndex]["partnerId"] = nil;
                self.helpMan[self.formationsIndex]["partnerModelId"] = nil;
                self.helpMan[self.formationsIndex]["icon"] = "";
                self.helpMan[self.formationsIndex]["type"] = nil;
                self.helpMan[self.formationsIndex]["power"] = nil;
                self.helpMan[self.formationsIndex]["realPower"] = nil;
                self.helpMan[self.formationsIndex]["state"] = 0;
                self.helpMan[self.formationsIndex]["weaponRank"] = nil
                heroData["state"] = 0;

                if self.isFriendBattle then
                    FireEvent(Config.EventType.FreshBorrowTeam, self.playerIds)
                end
            else
                for i = 1, #self.tabHeroPosData do
                    if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i]["partnerId"] == heroData["partnerId"] then
                        --data = logicMgr.HeroManager.setHeroState(heroData["partnerId"], false, EnumConst.HeroHeadStateEnum.BATTLE, self.formationType, hero);
                        self.tabHeroPosData[i]["partnerId"] = nil;
                        self.tabHeroPosData[i]["partnerModelId"] = nil;
                        self.tabHeroPosData[i]["icon"] = "";
                        self.tabHeroPosData[i]["type"] = nil;
                        self.tabHeroPosData[i]["power"] = nil;
                        self.tabHeroPosData[i]["realPower"] = nil;
                        self.formations[self.formationsIndex][i] = 0;
                        self.tabHeroPosData[i]["state"] = 0;
                        self.tabHeroPosData[i]["weaponRank"] = nil;
                        heroData["state"] = 0;
                        if self.isFriendBattle then
                            FireEvent(Config.EventType.FreshBorrowTeam, self.playerIds)
                        end
                        break ;
                    end
                end
            end
            if data ~= nil then
                local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
                if ctrlItem ~= nil then
                    ctrlItem.updateState(go, data);
                end
                self:rendererFormation();
            end
        else
            local bFull = true;
            if self:CanTeam(heroData["partnerModelId"]) then
                return
            end
            for i = 1, #self.tabHeroPosData do
                if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i]["partnerId"] == nil then
                    bFull = false;
                    break ;
                end
            end
            if bFull then
                if self.helpMan[self.formationsIndex] ~= nil and self.helpMan[self.formationsIndex]["partnerId"] == nil and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, true) then
                    --data = logicMgr.HeroManager.setHeroState(heroData["partnerId"], true, EnumConst.HeroHeadStateEnum.BATTLE, self.formationType, hero);
                    data.state = EnumConst.HeroHeadStateEnum.BATTLE
                    self.helpMan[self.formationsIndex]["partnerId"] = heroData["partnerId"];
                    self.helpManId[self.formationsIndex] = tostring(heroData["partnerId"]) or "0";
                    self.helpMan[self.formationsIndex]["partnerModelId"] = heroData["partnerModelId"];
                    self.helpMan[self.formationsIndex]["level"] = heroData["level"];
                    self.helpMan[self.formationsIndex]["star"] = heroData["star"];
                    self.helpMan[self.formationsIndex]["weaponLevel"] = heroData["weaponLevel"];
                    self.helpMan[self.formationsIndex]["type"] = heroData["type"];
                    self.helpMan[self.formationsIndex]["power"] = heroData["power"];
                    self.helpMan[self.formationsIndex]["realPower"] = heroData["realPower"];
                    self.helpMan[self.formationsIndex]["state"] = data["state"];
                    self.helpMan[self.formationsIndex]["weaponRank"] = logicMgr.HeroManager.GetWeaponQuality(heroData["partnerModelId"])
                else
                    UISysTips.AddMsg(getLanguage("Character_Tips1"));
                    return ;
                end
            else
                for i = 1, #self.tabHeroPosData do
                    if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i]["partnerId"] == nil then
                        data.state = EnumConst.HeroHeadStateEnum.BATTLE
                        --data = logicMgr.HeroManager.setHeroState(heroData["partnerId"], true, EnumConst.HeroHeadStateEnum.BATTLE, self.formationType, hero);
                        self.tabHeroPosData[i]["partnerId"] = heroData["partnerId"];
                        self.tabHeroPosData[i]["partnerModelId"] = heroData["partnerModelId"];
                        self.tabHeroPosData[i]["level"] = heroData["level"];
                        self.tabHeroPosData[i]["star"] = heroData["star"];
                        self.tabHeroPosData[i]["weaponLevel"] = heroData["weaponLevel"];
                        self.tabHeroPosData[i]["type"] = heroData["type"];
                        self.tabHeroPosData[i]["power"] = heroData["power"];
                        self.tabHeroPosData[i]["realPower"] = heroData["realPower"];
                        self.formations[self.formationsIndex][i] = heroData["partnerId"];
                        self.tabHeroPosData[i]["state"] = heroData["state"];
                        self.tabHeroPosData[i]["weaponRank"] = logicMgr.HeroManager.GetWeaponQuality(heroData["partnerModelId"])
                        if self.isFriendBattle then
                            self.clickIndex = i;
                            FireEvent(Config.EventType.BattleTeamClickIndex, self.clickIndex)
                        end
                        self:checkRestrain(self.tabHeroPosData[i]["partnerModelId"], i)
                        break ;
                    end
                end
            end
            
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
            if data ~= nil then
                if ctrlItem ~= nil then
                    ctrlItem.updateState(go, data);
                end
            end
            self:rendererFormation();
        end
        self:refreshCombinationSkill();
    end
end

-- 检查并播放克制关系
function UIBattleTeamEditor:checkRestrain(partnerModelId, index)
    if index > #self._counterpointList or partnerModelId == nil then
        return ;
    end
    if self.oppoFormations[self.formationsIndex] then
        if self.oppoFormations[self.formationsIndex][self._counterpointList[index]] then
            if logicMgr.HeroManager.GetHeroRestrain(partnerModelId, self.oppoFormations[self.formationsIndex][self._counterpointList[index]]["partnerModelId"]) then
                self:playRestrain(index, 1);
            end
        end
        for k, v in pairs(self.oppoFormations[self.formationsIndex]) do
            if v.partnerModelId ~= nil and self._counterpointList[k] == index and logicMgr.HeroManager.GetHeroRestrain(v.partnerModelId, partnerModelId) then
                self:playRestrain(k, 2);
            end
        end
    end
end

-- 播放克制关系 type=1 我方克制敌方,type=2 敌方克制我方,
function UIBattleTeamEditor:playRestrain(index, type)
    if index > #self.restrainObjList[type] then
        return ;
    end
    if self.playRestrainTimeList[type][index] then
        utimer.remove(self.playRestrainTimeList[type][index]);
    end
    self.restrainObjList[type][index].visible = true;
    self.restrainObjList[type][index].alpha = 1;
    local xx = self._restrainTime;
    self.playRestrainTimeList[type][index] = utimer.frameCall(function()
        xx = xx - 100;
        if xx <= 0 then
            self.restrainObjList[type][index].visible = false;
            self.playRestrainTimeList[type][index] = nil;
            return true;
        end
        self.restrainObjList[type][index].alpha = xx / self._restrainTime;
    end, 100, -1);
end

function UIBattleTeamEditor:CanTeam(partnerModelId)
    local isTip = nil
    if self.isFriendBattle then
        local ismy, index = logicMgr.FriendBattleManager.IsGoBattle(partnerModelId)
        if ismy and self.playerIds[index] and tonumber(tostring(self.playerIds[index])) ~= 0 then
            UISysTips.AddMsg("不能上阵相同的英雄")
            isTip = true
        end
    end
    return isTip
end

function UIBattleTeamEditor:BorrowInfo(msg)
    local self = UIBattleTeamEditor;
    local i = nil;
    local ishave
    for k, v in ipairs(self.tabHeroPosData) do
        if v and v["partnerId"] == nil then
            i = k
            break
        end
    end
    for k, v in ipairs(self.tabHeroPosData) do
        if v.partnerModelId == msg.partnerModelId and self.playerIds[k] ~= 0 then
            ishave = true
            i = k
            break
        end
    end
    if i then
        if i < 6 then
            if self.tabHeroPosData[i] ~= nil and self.tabHeroPosData[i]["partnerId"] == nil and not ishave then
                self.tabHeroPosData[i]["partnerId"] = msg.partnerId
                self.tabHeroPosData[i]["partnerModelId"] = msg.partnerModelId
                self.tabHeroPosData[i]["level"] = msg.level
                self.tabHeroPosData[i]["power"] = msg.power
                self.tabHeroPosData[i]["realPower"] = 0
                self.tabHeroPosData[i]["star"] = msg.star
                self.tabHeroPosData[i]["name"] = msg.name
                self.tabHeroPosData[i]["type"] = logicMgr.HeroManager.getHeroDatabyModelId(msg.partnerModelId)["type"]
                self.tabHeroPosData[i]["weaponRank"] = msg.weaponRank
                self.formations[self.formationsIndex][i] = msg.partnerId
                self.playerIds[i] = msg.playerId
            else
                self.tabHeroPosData[i]["partnerId"] = nil;
                self.tabHeroPosData[i]["partnerModelId"] = nil;
                self.tabHeroPosData[i]["type"] = nil;
                self.formations[self.formationsIndex][i] = 0;
                self.tabHeroPosData[i]["power"] = nil
                self.tabHeroPosData[i]["realPower"] = nil
                self.tabHeroPosData[i]["star"] = nil
                self.tabHeroPosData[i]["name"] = nil
                self.tabHeroPosData[i]["weaponRank"] = nil
                self.playerIds[i] = nil
            end
        else
            if self.helpMan[self.formationsIndex] ~= nil and int64ToNumber(self.helpManId[self.formationsIndex]) == int64ToNumber(msg.partnerId) then
                self.helpManId[self.formationsIndex] = "0"
                self.helpMan[self.formationsIndex]["partnerId"] = nil;
                self.helpMan[self.formationsIndex]["partnerModelId"] = nil;
                self.helpMan[self.formationsIndex]["type"] = nil;
                self.helpMan[self.formationsIndex]["power"] = nil;
                self.helpMan[self.formationsIndex]["realPower"] = nil;
                self.helpMan[self.formationsIndex]["star"] = nil
                self.helpMan[self.formationsIndex]["name"] = nil
                self.helpMan[self.formationsIndex]["weaponRank"] = nil
                self.playerIds[i] = nil
            else
                self.helpMan[self.formationsIndex]["partnerId"] = msg.partnerId;
                self.helpManId[self.formationsIndex] = tostring(msg.partnerId);
                self.helpMan[self.formationsIndex]["level"] = msg.level;
                self.helpMan[self.formationsIndex]["star"] = msg.star
                self.helpMan[self.formationsIndex]["weaponLevel"] = msg.weaponLevel
                self.helpMan[self.formationsIndex]["partnerModelId"] = msg.partnerModelId;
                self.helpMan[self.formationsIndex]["name"] = msg.name;
                self.helpMan[self.formationsIndex]["type"] = logicMgr.HeroManager.getHeroDatabyModelId(msg.partnerModelId, true)["type"];
                self.playerIds[i] = msg.playerId
                self.helpMan[self.formationsIndex]["power"] = msg.power
                self.helpMan[self.formationsIndex]["realPower"] = 0
                self.helpMan[self.formationsIndex]["weaponRank"] = msg.weaponRank
            end
        end
        logicMgr.FriendBattleManager.BattleTeam(self.tabHeroPosData, self.helpMan[self.formationsIndex])
        FireEvent(Config.EventType.FreshBorrowTeam, self.playerIds)
        self:rendererFormation();
    else
        UISysTips.AddMsg("上阵英雄已达到上限")
        return
    end
end

function UIBattleTeamEditor:changePosByIndex(idx1, idx2)
    local tempIdx;
    if idx2 ~= idx1 then
        if idx2 >= nodeCount + 1 then
            if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, true) then
                tempIdx = self.formations[self.formationsIndex][idx1]
                self.formations[self.formationsIndex][idx1] = self.helpManId[self.formationsIndex] or "0";
                if tempIdx == nil or tempIdx == "" then
                    tempIdx = "0";
                end
                self.helpManId[self.formationsIndex] = tostring(tempIdx);
                self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx1]["partnerModelId"], idx2)
                self:checkRestrain(self.helpMan[self.formationsIndex]["partnerModelId"], idx1)
            else
                return
            end
        elseif idx1 >= nodeCount + 1 then
            if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HelpMan, true) then
                tempIdx = self.formations[self.formationsIndex][idx2]
                self.formations[self.formationsIndex][idx2] = self.helpManId[self.formationsIndex] or "0";
                if tempIdx == nil or tempIdx == "" then
                    tempIdx = "0";
                end
                self.helpManId[self.formationsIndex] = tostring(tempIdx);
                self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx2]["partnerModelId"], idx1)
                self:checkRestrain(self.helpMan[self.formationsIndex]["partnerModelId"], idx2)
            else
                return
            end
        else
            tempIdx = self.formations[self.formationsIndex][idx1]
            self.formations[self.formationsIndex][idx1] = self.formations[self.formationsIndex][idx2];
            self.formations[self.formationsIndex][idx2] = tempIdx;
            self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx1]["partnerModelId"], idx2)
            self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx2]["partnerModelId"], idx1)
        end
        if self.isFriendBattle then
            local temp = self.playerIds[idx1]
            local temp2 = self.tabHeroPosData[idx1]
            if idx1 >= 6 then
                temp2 = self.helpMan[self.formationsIndex]
            end
            if self.playerIds[idx1] or self.playerIds[idx2] then
                self.playerIds[idx1] = self.playerIds[idx2]
                self.playerIds[idx2] = temp
                if idx1 >= 6 then
                    self.helpMan[self.formationsIndex] = self.tabHeroPosData[idx2]
                    self.tabHeroPosData[idx2] = temp2
                elseif idx2 >= 6 then
                    self.tabHeroPosData[idx1] = self.helpMan[self.formationsIndex]
                    self.helpMan[self.formationsIndex] = temp2
                else
                    self.tabHeroPosData[idx1] = self.tabHeroPosData[idx2]
                    self.tabHeroPosData[idx2] = temp2
                end
            end
        end
        if idx1 <= nodeCount then
            self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx1]["partnerModelId"], idx2)
        end
        if idx2 <= nodeCount then
            self:checkRestrain(self.tabHeroPosDataTemp[self.formationsIndex][idx2]["partnerModelId"], idx1)
        end
    end
    self:initFormation()
    self:rendererFormation()
    self:refreshCombinationSkill();
end

function UIBattleTeamEditor:setSelfFormationByType(fightType, param)
    --- 获取我方阵容
    self.formations = {}
    if fightType == nil then
        return
    end
    self.formationType = nil

    self.formationType = EnumConst.FormationType.FormationEditor

    
    SUPPORT_TEAMMATE_SITE = 6
    nodeCount = 5

    local defaultFormation
    if self.formationType == EnumConst.FormationType.FormationEditor then
        local index = logicMgr.FormationManager.GetFocus()
        local tb = logicMgr.FormationManager.GetEditorTeam(index, true)
        if tb then
            defaultFormation = tb.team
        end
    else
        defaultFormation = logicMgr.FormationManager.GetFormation(self.formationType);
    end

    -- local defaultFormation = logicMgr.FormationManager.GetFormation(self.formationType);
    local isFormationTips = logicMgr.FormationManager.checkDefFormationRedDotByType(formationType)
    
    for i = 1, self.formationsMax do
        self.formations[i] = {}
        self.helpManId[i] = "0";
        self.helpMan[i] = {}
        self.enemyHelpMan[i] = {}
        self.enemyHelpManId[i] = {}
        self.tabHeroPosDataTemp[i] = {}
        for j = 1, nodeCount do
            self.tabHeroPosDataTemp[i][j] = {}
        end
        for j = 1, nodeCount + 1 do
            self.formations[i][j] = "0"
        end
    end

    if defaultFormation ~= nil and #defaultFormation > 0 then
        if type(param) == "table" and param.formation then
            self.formations[1] = param.formation or {}
            self.helpManId[1] = self.formations[1][nodeCount + 1]
        else
            -- 给默认阵容赋值
            if type(defaultFormation[1]) == "table" then
                --阵容列表
                for i = 1, self.formationsMax do
                    if i <= #defaultFormation then
                        if type(defaultFormation[i]) ~= "table" then
                            defaultFormation[i] = {}
                            for sub_index = 1, nodeCount + 1 do
                                defaultFormation[i][sub_index] = "0"
                            end
                        end
                        self.formations[i] = defaultFormation[i]
                        self.helpManId[i] = self.formations[i][nodeCount + 1]
                    end
                end
            else
                -- 只是单个阵容
                self.formations[1] = defaultFormation
                self.helpManId[1] = self.formations[1][nodeCount + 1]
            end
        end
    else
        if param and param.formation then
            if self.formationsMax == 1 then
                self.formations[1] = param.formation or {}
                self.helpManId[1] = param.formation and param.formation[nodeCount + 1] or "0"
            else
                for i = 1, self.formationsMax do
                    self.formations[i] = param.formation[i] or {}
                    self.helpManId[i] = self.formations[i][nodeCount + 1]
                end
            end
        end
    end
    for i = 1, #self.formations do
        for k, v in pairs(self.formations[i]) do
            if v ~= nil and (v ~= 0 or v ~= "0") then
                local state = EnumConst.HeroHeadStateEnum.BATTLE;
                for u = 1, #self.tableHeros do
                    if tostring(self.tableHeros[u].partnerId) == tostring(v) then
                        --local data = logicMgr.HeroManager.setHeroState(self.tableHeros[u].partnerId, true, state, self.formationType, self.tableHeros[u])
                        self.tableHeros[u]["state"] = 4
                        break
                    end
                end
            end
        end
    end
    local state = EnumConst.HeroHeadStateEnum.BATTLE
    for u = 1, #self.tableHeros do
        if tostring(self.tableHeros[u].partnerId) == tostring(self.helpManId[self.formationsIndex]) then
            --local data = logicMgr.HeroManager.setHeroState(self.tableHeros[u].partnerId, true, state, self.formationType, self.tableHeros[u])
            self.tableHeros[u]["state"] = 4
            break
        end
    end
    if fightType == EnumConst.FightTypeConst.Expedition then
        logicMgr.ExpeditionMgr.SetHeroDeadFlag()
    end
end

function UIBattleTeamEditor:setOppoFormationByType(_fightType, _param)
    -- 获取敌方阵容
    if _param ~= nil and type(_param) == "table" and _param.supSkillId then
        self.otherSupSkill = _param.supSkillId
    end
    currentFightType = _fightType
    self.oppoFormations = {}
    -- utimer.delayCall(function()
    --     AudioManager.Play(102)
    -- end, 100)

    FightManager.SetBGMSwitchByBattleType(_fightType)
    if _fightType == EnumConst.FightTypeConst.DUNGEON then
        --播放 Play_mus_battle
        -- AudioManager.SetSwitch("battle_steps", "arr")
        AudioManager.Play(114)

        --进入布阵界面
        TAManager.TrackByDictionary("ui_battle_team_join")

        local monsters = logicMgr.MapManager.getMonster();
        self.powerEnemyNum = {};
        for i = 1, #monsters do
            local OppoFormation = {};
            local types = decodeJsonStrToTabel(monsters[i].occupation);
            local typesnum = 1
            for k, v in pairs(monsters[i]["team"]) do
                if k <= 5 then
                    OppoFormation[k] = {}
                    OppoFormation[k]["partnerId"] = v[1]
                    OppoFormation[k]["partnerModelId"] = v[1]
                    OppoFormation[k]["level"] = v[2]
                    OppoFormation[k]["star"] = v[4]
                    OppoFormation[k]["weaponLevel"] = 0
                    OppoFormation[k]["icon"] = ""
                    OppoFormation[k]["type"] = types[typesnum]
                    OppoFormation[k]["state"] = 0
                    typesnum = typesnum + 1
                elseif k == 6 then
                    self.enemyHelpMan[i] = {};
                    self.enemyHelpManId[i] = v[1]
                    self.enemyHelpMan[i]["partnerId"] = v[1]
                    self.enemyHelpMan[i]["partnerModelId"] = v[1]
                    self.enemyHelpMan[i]["level"] = v[2]
                    self.enemyHelpMan[i]["star"] = v[4]
                    self.enemyHelpMan[i]["weaponLevel"] = 0
                    self.enemyHelpMan[i]["icon"] = ""
                    self.enemyHelpMan[i]["type"] = types[typesnum]
                    self.enemyHelpMan[i]["state"] = 0
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
            table.insert(self.powerEnemyNum, monsters[i].power)
        end

    elseif _fightType == EnumConst.FightTypeConst.INSTANCE then
        local mythicFormatios = logicMgr.MythicDungeonsManager.getFormationInfos()
        for i = 1, #mythicFormatios do
            local OppoFormation = {};
            for k, v in pairs(mythicFormatios[i]["members"]) do
                if k <= 5 then
                    OppoFormation[k] = {}
                    OppoFormation[k]["partnerId"] = v["info"][1]
                    OppoFormation[k]["partnerModelId"] = v["info"][1]
                    OppoFormation[k]["level"] = v["info"][2]
                    OppoFormation[k]["star"] = v["info"][4]
                    OppoFormation[k]["weaponLevel"] = 0
                    OppoFormation[k]["icon"] = ""
                    OppoFormation[k]["state"] = 0
                elseif k == 6 then
                    self.enemyHelpMan[i] = {}
                    self.enemyHelpManId[i] = v["info"][1]
                    self.enemyHelpMan[i]["partnerId"] = v["info"][1]
                    self.enemyHelpMan[i]["partnerModelId"] = v["info"][1]
                    self.enemyHelpMan[i]["level"] = v["info"][2]
                    self.enemyHelpMan[i]["star"] = v["info"][4]
                    self.enemyHelpMan[i]["weaponLevel"] = 0
                    self.enemyHelpMan[i]["icon"] = ""
                    self.enemyHelpMan[i]["state"] = 0
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
        local key = G.dataTable["t_mythicdungeons"][tostring(_param)]["f_MythicDungeonsMonsterTeamId"]
        self.powerEnemyNum = G.dataTable["t_mythicdungeonsmonsterteam"][tostring(key)]["f_DispPower"]

    elseif _fightType == EnumConst.FightTypeConst.TOWER then
        local curTowerType = logicMgr.TowerManager.getClimbType()
        --职业爬塔
        if G.dataTable["t_towertype"][tostring(curTowerType)].f_Group == EnumConst.TowerType.Advanced then
            self:AdvancedTowerDisableBtn()
        end
        local teamInfo = logicMgr.TowerManager.getTowerMonsterTeam(curTowerType)
        if teamInfo ~= nil then
            local OppoFormation = {};
            for k, v in pairs(teamInfo.team) do
                if k <= 5 then
                    OppoFormation[k] = {}
                    OppoFormation[k]["partnerId"] = v[1]
                    OppoFormation[k]["partnerModelId"] = v[1]
                    OppoFormation[k]["level"] = v[2]
                    OppoFormation[k]["star"] = v[4]
                    OppoFormation[k]["weaponLevel"] = 0
                    OppoFormation[k]["icon"] = ""
                    OppoFormation[k]["state"] = 0
                elseif k == 6 then
                    self.enemyHelpMan[1] = {}
                    self.enemyHelpManId[1] = v[1]
                    self.enemyHelpMan[1]["partnerId"] = v[1]
                    self.enemyHelpMan[1]["partnerModelId"] = v[1]
                    self.enemyHelpMan[1]["level"] = v[2]
                    self.enemyHelpMan[1]["star"] = v[4]
                    self.enemyHelpMan[1]["weaponLevel"] = 0
                    self.enemyHelpMan[1]["icon"] = ""
                    self.enemyHelpMan[1]["state"] = 0
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
        self.powerEnemyNum = teamInfo.power
    elseif _fightType == EnumConst.FightTypeConst.ARENA then
        local teamInfo = nil
        local teamCrossPower = nil
        if param and param.arena_type == EnumConst.ArenaBattleType.Normal then
            teamInfo = logicMgr.ArenaManager.getOppoMonster(_param.playerId)
        elseif param and param.arena_type == EnumConst.ArenaBattleType.Cross then
            teamInfo = logicMgr.ArenaManager.getCrossOppoMonster(_param.playerId)
        elseif param and param.arena_type == EnumConst.ArenaBattleType.TeamCross then
            local temp_team_info, crossPower = logicMgr.ArenaManager.getCrossTeamOppoMonster(_param.playerId)
            if temp_team_info ~= nil then
                for i = 1, #temp_team_info do
                    local OppoFormation = {}
                    for k, v in pairs(temp_team_info[i]) do
                        if k <= 5 then
                            OppoFormation[k] = {}
                            OppoFormation[k]["partnerId"] = v.partnerId
                            OppoFormation[k]["partnerModelId"] = v.partnerModelId
                            OppoFormation[k]["level"] = v.level
                            OppoFormation[k]["star"] = v.star
                            OppoFormation[k]["weaponLevel"] = v.weaponLevel or 0
                            OppoFormation[k]["weaponRank"] = v.weaponRank or 1
                            OppoFormation[k]["icon"] = ""
                            OppoFormation[k]["state"] = 0
                        elseif k == 6 then
                            self.enemyHelpMan[i] = {}
                            self.enemyHelpManId[i] = v.partnerId
                            self.enemyHelpMan[i]["partnerId"] = v.partnerId
                            self.enemyHelpMan[i]["partnerModelId"] = v.partnerModelId
                            self.enemyHelpMan[i]["level"] = v.level
                            self.enemyHelpMan[i]["star"] = v.star
                            self.enemyHelpMan[i]["weaponLevel"] = v.weaponLevel or 0
                            self.enemyHelpMan[i]["weaponRank"] = v.weaponRank or 1
                            self.enemyHelpMan[i]["icon"] = ""
                            self.enemyHelpMan[i]["state"] = 0
                        end
                    end
                    table.insert(self.oppoFormations, OppoFormation)
                end
            end
            if crossPower ~= nil then
                teamCrossPower = crossPower;
            end
        else
            error("错误竞技场类型" .. tostring(param and param.arena_type))
        end
        if teamInfo ~= nil then
            local OppoFormation = {}
            for i = 1, #teamInfo do
                if i <= nodeCount then
                    local index = teamInfo[i]["index"]
                    OppoFormation[index] = teamInfo[i]
                elseif i == nodeCount + 1 then
                    self.enemyHelpManId[self.formationsIndex] = teamInfo[i]["partnerId"]
                    self.enemyHelpMan[self.formationsIndex] = teamInfo[i]
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
        if teamCrossPower ~= nil then
            self.powerEnemyNum = teamCrossPower;
        else
            self.powerEnemyNum = _param.power == nil and 0 or _param.power
        end
    elseif _fightType == EnumConst.FightTypeConst.ARENARECORD then
        local teamInfo = nil
        if type(param) == "table" and param.arena_type == EnumConst.ArenaBattleType.Normal then
            teamInfo = logicMgr.ArenaManager.geRecordMonster(_param.id)
        elseif type(param) == "table" and param.arena_type == EnumConst.ArenaBattleType.Cross then
            teamInfo = logicMgr.ArenaManager.getCrossRecordMonster(_param.id)
        elseif type(param) == "table" and param.arena_type == EnumConst.ArenaBattleType.TeamCross then
            local temp_teamInfo = logicMgr.ArenaManager.getCrossTeamRecordMonster(_param.id)
            if temp_teamInfo ~= nil then
                for k = 1, #temp_teamInfo do
                    local OppoFormation = {}
                    local temp_info = temp_teamInfo[k]
                    for i = 1, #temp_info.formation do
                        for j = 1, #temp_info.members do
                            if temp_info.members[j].partnerId == temp_info.formation[i] then
                                if i <= 5 then
                                    OppoFormation[i] = temp_info.members[j]
                                elseif i == 6 then
                                    self.enemyHelpManId[k] = temp_info.members[j]["partnerId"]
                                    self.enemyHelpMan[k] = temp_info.members[j]
                                end
                            end
                        end
                    end
                    table.insert(self.oppoFormations, OppoFormation)
                end
            end
        else
            error("错误竞技场类型")
        end
        if teamInfo ~= nil then
            local OppoFormation = {}
            for i = 1, #teamInfo.formation do
                for j = 1, #teamInfo.members do
                    if teamInfo.members[j].partnerId == teamInfo.formation[i] then
                        if i <= 5 then
                            OppoFormation[i] = teamInfo.members[j]
                        elseif i == 6 then
                            self.enemyHelpManId[self.formationsIndex] = teamInfo.members[j]["partnerId"]
                            self.enemyHelpMan[self.formationsIndex] = teamInfo.members[j]
                        end
                    end
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
        self.powerEnemyNum = _param.power == nil and 0 or _param.power

    elseif _fightType == EnumConst.FightTypeConst.Expedition then
        local info = logicMgr.ExpeditionMgr.GetStageInfo(_param);
        if info ~= nil then
            local OppoFormation = {};
            local formation = info.formation
            for k, v in pairs(formation) do
                if k <= 5 and v.hp > 0 then
                    local star = dataTable.getDataTableByStringId("t_hero", v.modelId, "f_HeroInitialStar")
                    table.insert(OppoFormation, { partnerModelId = v.modelId, partnerId = k, level = v.level, star = star, weaponLevel = 0 })
                elseif k == 6 and v.hp > 0 then
                    local star = dataTable.getDataTableByStringId("t_hero", v.modelId, "f_HeroInitialStar")
                    self.enemyHelpManId[self.formationsIndex] = k
                    self.enemyHelpMan[self.formationsIndex] = { partnerModelId = v.modelId, partnerId = k, level = v.level, star = star, weaponLevel = 0 };
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
            self.powerEnemyNum = info.power
        end
    elseif _fightType == EnumConst.FightTypeConst.TRIAL then
        local OppoFormation = {}
        for i = 1, 5 do
            local item = _param[i] or {}
            if item["partnerId"] == "0" then
                item["partnerId"] = nil
            end
            table.insert(OppoFormation, item)
        end
        table.insert(self.oppoFormations, OppoFormation)
        self.powerEnemyNum = logicMgr.TrialsManager.getBossPower()
    elseif _fightType == EnumConst.FightTypeConst.FriendAttack then
        local teamInfo, skillId = logicMgr.FriendBattleManager.GetFormationById(_param)
        self.otherSupSkill = skillId;
        self.powerEnemyNum = 0
        if teamInfo ~= nil then
            local OppoFormation = {};
            for k, v in pairs(teamInfo) do
                local config = v.partner
                if k <= 5 then
                    OppoFormation[k] = {};
                    OppoFormation[k]["partnerId"] = config.partnerId
                    OppoFormation[k]["partnerModelId"] = config.partnerModelId
                    OppoFormation[k]["level"] = config.level
                    OppoFormation[k]["star"] = config.star
                    OppoFormation[k]["weaponLevel"] = config.weaponLevel
                    OppoFormation[k]["icon"] = "";
                    OppoFormation[k]["state"] = nil;
                    OppoFormation[k]["state"] = 0;
                    self.powerEnemyNum = self.powerEnemyNum + config.fightVal
                elseif k == 6 then
                    self.enemyHelpMan[1] = {};
                    self.enemyHelpManId[1] = config
                    self.enemyHelpMan[1]["partnerId"] = config.partnerId
                    self.enemyHelpMan[1]["partnerModelId"] = config.partnerModelId
                    self.enemyHelpMan[1]["level"] = config.level
                    self.enemyHelpMan[1]["star"] = config.star
                    self.enemyHelpMan[1]["weaponLevel"] = config.weaponLevel
                    self.enemyHelpMan[1]["icon"] = "";
                    self.enemyHelpMan[1]["state"] = nil;
                    self.enemyHelpMan[1]["state"] = 0;
                    self.powerEnemyNum = self.powerEnemyNum + config.fightVal
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
    elseif _fightType == EnumConst.FightTypeConst.RankBattle then
        if logicMgr.RankBattleManager.BanPick() then
            local _, enemyformation = logicMgr.RankBattleManager.GetBPFormation()
            local OppoFormation = {};
            for k, v in pairs(enemyformation) do
                local config = logicMgr.RankBattleManager.SeasonBanHero(v)
                if config then
                    if k <= 5 then
                        OppoFormation[k] = {}
                        OppoFormation[k]["partnerId"] = config.partnerId
                        OppoFormation[k]["partnerModelId"] = config.partnerModelId
                        OppoFormation[k]["level"] = 300
                        OppoFormation[k]["star"] = 150
                        OppoFormation[k]["weaponLevel"] = 0
                        OppoFormation[k]["icon"] = ""
                        OppoFormation[k]["state"] = 0
                    elseif k == 6 then
                        self.enemyHelpMan[1] = {}
                        self.enemyHelpManId[1] = config
                        self.enemyHelpMan[1]["partnerId"] = config.partnerId
                        self.enemyHelpMan[1]["partnerModelId"] = config.partnerModelId
                        self.enemyHelpMan[1]["level"] = 300
                        self.enemyHelpMan[1]["star"] = 150
                        self.enemyHelpMan[1]["weaponLevel"] = 0
                        self.enemyHelpMan[1]["icon"] = ""
                        self.enemyHelpMan[1]["state"] = 0
                    end
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
    elseif _fightType == EnumConst.FightTypeConst.FriendCompeteBattle or _fightType == EnumConst.FightTypeConst.GuildFriendCompeteBattle then
        FightManager.SetBGMSwitchByBattleType(EnumConst.FightTypeConst.TRIAL)
        AudioManager.SetSwitch("Battle_SwitchGroup", "arena")
        local info = logicMgr.FriendManager.GetFriendCompeteBattleInfo()
        if _param.isFriend then
            self.competeBattleWinsCtrl:SetSelectedIndex(1)
            self.otherWinTimerText.text = param.competeTimes - param.wins
            self.myWinTimerText.text = param.wins
        else
            self.competeBattleWinsCtrl:SetSelectedIndex(0)
        end

        local teamInfo = info.formation
        local powerSum = 0
        if teamInfo ~= nil then
            local OppoFormation = {}
            for i = 1, #teamInfo do
                teamInfo[i].weaponLevel = teamInfo[i].weaponLv;
                if i <= 5 then
                    if tonumber(tostring(teamInfo[i]["partnerId"])) ~= 0 then
                        OppoFormation[i] = teamInfo[i];
                        powerSum = powerSum + teamInfo[i].fightVal
                    else
                        OppoFormation[i] = teamInfo[i];
                        OppoFormation[i]["partnerId"] = nil;
                    end
                elseif i == 6 then
                    if tonumber(tostring(teamInfo[i]["partnerId"])) ~= 0 then
                        self.enemyHelpManId[self.formationsIndex] = teamInfo[i]["partnerId"];
                        self.enemyHelpMan[self.formationsIndex] = teamInfo[i];
                        powerSum = powerSum + teamInfo[i].fightVal;
                    else
                        self.enemyHelpManId[self.formationsIndex] = nil;
                    end
                end
            end
            table.insert(self.oppoFormations, OppoFormation)
        end
        self.powerEnemyNum = powerSum
    elseif _fightType == EnumConst.FightTypeConst.Plunder then
        if param and param.oppo_formation then
            local powerSum = 0
            local teamInfo = param.oppo_formation
            if teamInfo ~= nil then
                local OppoFormation = {}
                for i = 1, #teamInfo do
                    if i <= 5 then
                        if teamInfo[i] and tonumber(tostring(teamInfo[i]["partnerId"])) ~= 0 then
                            OppoFormation[i] = teamInfo[i]
                            if teamInfo[i].power ~= nil then
                                powerSum = powerSum + teamInfo[i].power
                            end
                        else
                            OppoFormation[i] = teamInfo[i]
                            OppoFormation[i]["partnerId"] = nil
                        end
                    elseif i == 6 then
                        if teamInfo[i] and tonumber(tostring(teamInfo[i]["partnerId"])) ~= 0 then
                            self.enemyHelpManId[self.formationsIndex] = teamInfo[i]["partnerId"]
                            self.enemyHelpMan[self.formationsIndex] = teamInfo[i]
                            if teamInfo[i].power ~= nil then
                                powerSum = powerSum + teamInfo[i].power
                            end
                        else
                            self.enemyHelpManId[self.formationsIndex] = nil
                        end
                    end
                end
                table.insert(self.oppoFormations, OppoFormation);
            end
            self.powerEnemyNum = powerSum
        end
    elseif _fightType == EnumConst.FightTypeConst.GuildBattlePlus then
        self.powerEnemyNum = {};
        if param and param.oppo_formation then
            for j = 1, self.formationsMax do
                local powerSum = 0
                local teamInfo = param.oppo_formation[j]
                if teamInfo ~= nil then
                    local OppoFormation = {}
                    for i = 1, #teamInfo do
                        if i <= 5 then
                            if teamInfo[i] and next(teamInfo[i]) ~= nil then
                                OppoFormation[i] = teamInfo[i]
                                if teamInfo[i].power ~= nil then
                                    powerSum = powerSum + tonumber(tostring(teamInfo[i].power))
                                end
                            else
                                OppoFormation[i] = teamInfo[i]
                                OppoFormation[i]["partnerId"] = nil
                            end
                        elseif i == 6 then
                            if teamInfo[i] and next(teamInfo[i]) ~= nil then
                                self.enemyHelpManId[j] = teamInfo[i]["partnerId"]
                                self.enemyHelpMan[j] = teamInfo[i]
                                if teamInfo[i].power ~= nil then
                                    powerSum = powerSum + tonumber(tostring(teamInfo[i].power))
                                end
                            else
                                self.enemyHelpManId[j] = nil
                            end
                        end
                    end
                    table.insert(self.oppoFormations, OppoFormation);
                    self.powerEnemyNum[j] = powerSum
                else
                    table.insert(self.oppoFormations, {});
                    self.enemyHelpManId[j] = nil
                    self.powerEnemyNum[j] = 0
                end
            end

        end
    end
end

function UIBattleTeamEditor:onClickBack1()
    -- local flag = false;
   
    -- if flag then
    --     local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    --     pop.Init("62", function(b)
    --         if b then
    --             self:onClickBack()
    --         end
    --     end);
    -- else
    --     self:onClickBack()
    -- end
    -- partnerHandler.clearInteractionSaveData()
    closeUI(PanelResNames.UIBattleTeamEditor)
end

function UIBattleTeamEditor:onClickBack()
    local self = UIBattleTeamEditor
    if self.isFriendBattle then
        closeUI(PanelNames.UITeam)
    end
    if self.formationType == EnumConst.FightTypeConst.RankBattle then
        local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
        logicMgr.HeroManager.AllRestRankHero()
        pop.Init("34", function(b)
            if b then
                RankBattleHandler.ReqRankBattleQuitMatch()
                closeUI(PanelResNames.UIRankBattleTeam)
                closeUI(PanelNames.UIBattleTeamEditor)
            end
        end);
    else
        closeUI(PanelNames.UIBattleTeamEditor)
    end
    for i = 1, 2 do
        for k, v in pairs(self.playRestrainTimeList[i]) do
            if v then
                utimer.remove(v)
            end
        end
        self.playRestrainTimeList[i] = {}
    end
    --if self.isNeedOpenHeadMenu then
    --    showUI(PanelNames.UIHeadMenu, true)
    --end
    dungeonHandler.reqQuitGroupBoss()
    logicMgr.BattlePlaybackManager.SetGroupBossHistory()
    if self.backFunction ~= nil then
        self.backFunction()
    end
end
function UIBattleTeamEditor:DelayEnableClick()
    self.isClickBattle = false
end

function UIBattleTeamEditor:onClickBoss()
    if self.isClickBattle then
        return
    end
    self.isClickBattle = true;
    self:TimeCall(self.DelayEnableClick, 1500)
    if currentFightType == EnumConst.FightTypeConst.DUNGEON then
        TAManager.TrackByDictionary("ui_battle_team_click_fight")
    elseif currentFightType == EnumConst.FightTypeConst.ARENA then
    elseif currentFightType == EnumConst.FightTypeConst.Expedition then
        TAManager.TrackByDictionary("expedition_battle_click_fight", { expedition_stage_id = ExpeditionMgr.GetCurStageId() })
    elseif currentFightType == EnumConst.FightTypeConst.Expedition then
        -- todo
    end
    local self = UIBattleTeamEditor
    for i = 1, self.formationsMax do
        if self.helpManId[i] ~= 0 and self.formations[i] then
            self.formations[i][nodeCount + 1] = self.helpManId[i] or "0"
        end
        for j = 1, nodeCount do
            if self.formations[i][j] == nil then
                self.formations[i][j] = "0"
            end
        end
    end
    if self.checkFunction ~= nil and not self.checkFunction(self.formations) then
        --AudioManager.Play(2010)
        return
    end

    if self.formationType == EnumConst.FormationType.TeamCrossArenaDef
            or self.formationType == EnumConst.FormationType.TeamCrossArenaAtk then
        local flag = false
        local formation = self.formations[self.formationsIndex]
        for k = 1, #formation do
            if k <= nodeCount then
                if formation[k] ~= nil and tonumber(tostring(formation[k])) ~= 0 then
                    flag = true
                    break
                end
            end
        end
        if not flag then
            UISysTips.AddMsg("每个阵容至少需要上阵一名英雄")
            AudioManager.Play(2010)
            self.ctrlNumTeams:SetSelectedIndex(self.formationsIndex)
            return
        end
    end

    if self.formationType == EnumConst.FormationType.MythicDungeons and self.formationsIndex == 1 then
        self.ctrlNumTeams.selectedIndex = 2
        self:onClickItemIndex(2)
        -- AudioManager.Play(1033)
        self.isClickBattle = false;
        return
    elseif self.formationType == EnumConst.FormationType.TeamCrossArenaDef
            or self.formationType == EnumConst.FormationType.TeamCrossArenaAtk
    then
        if self.formationsIndex == 1 then
            self.ctrlNumTeams:SetSelectedIndex(2)
            self:onClickItemIndex(2)
            -- AudioManager.Play(1033)
            self.isClickBattle = false
            return
        elseif self.formationsIndex == 2 then
            self.ctrlNumTeams:SetSelectedIndex(3)
            self:onClickItemIndex(3)
            -- AudioManager.Play(1033)
            self.isClickBattle = false
            return
        end
    elseif self.formationType == EnumConst.FormationType.GuildBattlePlus then
        for i = self.formationsIndex + 1, self.formationsMax do
            if not (param.formationIsOver and param.formationIsOver[i]) then
                local nextIndex = i;
                self.ctrlNumTeams:SetSelectedIndex(nextIndex)
                self:onClickItemIndex(nextIndex)
                -- AudioManager.Play(1033)
                self.isClickBattle = false
                return
            end
        end
    else
        if self.formationsIndex < self.formationsMax then
            local nextIndex = self.formationsIndex + 1;
            self.ctrlNumTeams:SetSelectedIndex(nextIndex)
            self:onClickItemIndex(nextIndex)
            self.isClickBattle = false
            return
        end
    end
    if self.battleBossFunction ~= nil then
        if self.formations then
            local fflag = true
            for i = 1, #self.formations do
                -- 多队推图只检测当前队
                if fightType == EnumConst.FightTypeConst.DUNGEON
                then
                    i = self.formationsIndex
                    -- elseif (self.formationType == EnumConst.FormationType.TeamCrossArenaAtk
                    --     or self.formationType == EnumConst.FormationType.TeamCrossArenaDef )
                    --     and fightType == EnumConst.FightTypeConst.ARENA
                    -- then
                    --     i = self.formationsIndex
                end
                local flag = false;
                for k = 1, #self.formations[i] do
                    if k <= nodeCount then
                        if self.formations[i][k] ~= nil and tonumber(tostring(self.formations[i][k])) ~= 0 then
                            flag = true
                            break
                        end
                    end
                end
                if fightType == EnumConst.FightTypeConst.GuildBattlePlus then
                    if param.formationIsOver and param.formationIsOver[i] then
                        flag = true
                    end
                end
                if not flag then
                    fflag = false
                    UISysTips.AddMsg("每个阵容至少需要上阵一名英雄")
                    AudioManager.Play(2010)
                    self.isClickBattle = false
                    break
                end
                if fightType == EnumConst.FightTypeConst.DUNGEON then
                    break
                    -- elseif ( self.formationType == EnumConst.FormationType.TeamCrossArenaAtk
                    --     or self.formationType == EnumConst.FormationType.TeamCrossArenaDef )
                    --     and fightType == EnumConst.FightTypeConst.ARENA
                    -- then
                    --     break
                end
            end
            if fflag then
                --if (self.formationType == EnumConst.FormationType.ArenaDef and fightType == EnumConst.FightTypeConst.ARENA)
                --        or self.formationType == EnumConst.FormationType.CrossArenaDef
                --        --or self.formationType == EnumConst.FormationType.FriendDefend
                --        or self.formationType == EnumConst.FormationType.PlunderBattle then
                if self.btnController.selectedIndex == 1 then
                    local flag = false;
                    for i = 1, #self.formations do
                        for k, v in pairs(self.formations[i]) do
                            local level = logicMgr.HeroManager.getHeroShowLevelByPartnerId(tostring(v));
                            if tonumber(level) == 1 then
                                if self.formationType ~= EnumConst.FormationType.FriendDefend and self.formationType ~= EnumConst.FormationType.CrossArenaDef
                                        and self.formationType ~= EnumConst.FormationType.TeamCrossArenaDef then
                                    -- UISysTips.AddMsg(getLanguage("DefendRedTips"));
                                end
                                flag = true
                                break
                            end
                        end
                        if flag then
                            break
                        end
                    end
                end
                for i = 1, 2 do
                    for k, v in pairs(self.playRestrainTimeList[i]) do
                        if v then
                            utimer.remove(v)
                        end
                    end
                    self.playRestrainTimeList[i] = {}
                end
                self.battleInfo.myHelpManId = self.helpManId
                self.battleInfo.enemyHelpManId = self.enemyHelpManId

                local tempForms = {};
                for i = 1, #self.oppoFormations do
                    local form = clone(self.oppoFormations[i]);
                    table.insert(form, self.enemyHelpMan[i])
                    table.insert(tempForms, form)
                end
                BattleSceneCacheResouce:CacheBattleFormation(self.formations, tempForms)
                FightManager.SetMyTeam(self.tabHeroPosData, self.helpMan[self.formationsIndex].partnerModelId)
                if self.isFriendBattle then
                    self.battleBossFunction(UIBattleTeamEditor:SetFriendBattleFormation())
                    closeUI(PanelNames.UIBattleTeamEditor)
                    closeUI(PanelResNames.UITeam)
                    FriendBattleHandler.ReqFriendBattleInfo()
                else
                    local mapCfg = MapManager.getMapcfg();
                    if not string.IsNilOrEmpty(mapCfg.f_ReportAddress) then
                        --前四关直接播放战报
                        local id = mapCfg.f_ReportAddress
                        BattlePlaybackManager.playReport(id)
                    end
                    FightManager.paramTeamBonus = {}
                    FightManager.paramTeamBonus.tabHeroPosData = clone(self.tabHeroPosData);
                    FightManager.paramTeamBonus.helpMan = clone(self.helpMan);
                    self.battleBossFunction(self.formations, self.oppoFormations, self.battleInfo, self.formationsIndex)
                    
                end
            end
        end
    end
end

function UIBattleTeamEditor:onClickManual()
    -- 攻略
    if fightType == EnumConst.FightTypeConst.DUNGEON then
        local formation_type = logicMgr.BattlePlaybackManager.GetFormationType()
        showUI(PanelNames.UIChapterRecord, nil, EnumConst.FightTypeConst.DUNGEON, nil, function()
            UIBattle.onClickBoss()
        end, nil, formation_type)
    end
end

function UIBattleTeamEditor.processHeroData(heroData, data, _data)
    heroData.partnerId = data.partnerId
    heroData.partnerModelId = data.partnerModelId
    heroData.level = data.level
    heroData.star = data.star
    local _heroData = logicMgr.HeroManager.getHeroDatabyModelId(heroData.partnerModelId)
    if _heroData then
        heroData.icon = _heroData.icon
    end
    heroData.type = data.type
    heroData.isDead = false
    if data.isOver and _data and _data.battleDetail then
        for k, v in pairs(_data.battleDetail) do
            if heroData.partnerModelId == v.partnerModelId then
                heroData.isDead = tonumber(tostring(v.hp)) <= 0;
            end
        end
    end
end

function UIBattleTeamEditor:onClick_CloseTeamEditor()
    self.ctr_teamListShow.selectedIndex = 0
end

function UIBattleTeamEditor:OnClickChallengeBtnAdd()
    if fightType ~= EnumConst.FightTypeConst.DarkStreet then
        return
    end
    local cost = dataTable.getGlobalString(546)
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop);
    pop.Init("76", function(b)
        if b then
            logError("等待服务器接入")
        end
    end, cost[2], logicMgr.DarkStreetMgr.GetRemainBuyTimes(), cost[1]);
end
function UIBattleTeamEditor:SetFriendBattleFormation()
    local heros = {}
    for i = 1, nodeCount + 1 do
        local config = self.tabHeroPosData[i]
        if i == 6 then
            config = self.helpMan[self.formationsIndex]
        end
        heros[i] = FriendBattleFormation.New()
        heros[i]["partner"] = PartnerInfo.New()
        heros[i]["partner"]["partnerModelId"] = (config and config.partnerModelId) and config.partnerModelId or 0
        heros[i]["partner"]["level"] = (config and config.level) and config.level or 0
        heros[i]["partner"]["star"] = (config and config.star) and config.star or 0
        heros[i]["partner"]["sameNum"] = 0
        heros[i]["partner"]["skinId"] = 0
        heros[i]["partner"]["fightVal"] = (config and config.power) and config.power or 0
        heros[i]["partner"]["fightVal2"] = (config and config.realPower) and config.realPower or 0
        heros[i]["partner"]["activateBondIds"] = {}
        heros[i]["partner"]["weaponLv"] = 0
        heros[i]["partner"]["weaponRank"] = config.weaponRank or 1
        heros[i]["partner"]["skinId"] = 0
        heros[i]["partner"]["favorLv"] = 0
        heros[i]["partner"]["favorExp"] = 0
        heros[i]["partner"]["favorRewardGetLv"] = 0
        heros[i]["partner"]["lastInteractTime"] = 0
        heros[i]["partner"]["interactInfos"] = {}
        local partnerId = config.partnerId
        if partnerId ~= 0 then
            heros[i]["partner"]["partnerId"] = partnerId and tostring(partnerId) or "0"
        else
            heros[i]["partner"]["partnerId"] = "0"
        end
        if self.playerIds[i] then
            heros[i]["playerId"] = tostring(self.playerIds[i])
        else
            heros[i]["playerId"] = "0"
        end
    end
    return heros;
end

function UIBattleTeamEditor.onClickChapterReward()
    showUI(PanelNames.UIChapterRewardNew);
end

function UIBattleTeamEditor:RefreshChapterRewardBtn()
    local itemModelId;
    local isEndLevel = logicMgr.MapManager.IsEndChapterMapId(MapManager.getMapId());
    local curChapter = logicMgr.MapManager.GetCurrentChapterId();
    local taskCfg;
    if isEndLevel then
        local hasReward, rewardGet = logicMgr.MapManager.GetChapterReward(MapManager.getMapId());
        local nextChapterTaskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter + 1);
        if (hasReward and not rewardGet) or (nextChapterTaskCfg == nil) then
            --当前章节奖励未领取
            taskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter);
            self.btnChapterRewardTips.text = "";
        else
            --显示下一章节奖励
            taskCfg = nextChapterTaskCfg;
            local maxMapCfg = MapManager.GetChapterMaxStageNum(curChapter + 1);
            self.btnChapterRewardTips.text = string.format(getLanguage("ChapterRewardText3"), maxMapCfg.f_StageNum);
        end
    else
        taskCfg = logicMgr.MapManager.GetChapterRewardCfg(curChapter);
        local curMapCfg = logicMgr.MapManager.getMapcfg();
        local maxMapCfg = MapManager.GetChapterMaxStageNum(curChapter);
        self.btnChapterRewardTips.text = string.format(getLanguage("ChapterRewardText3"), maxMapCfg.f_StageNum - curMapCfg.f_StageNum);
    end
    if taskCfg ~= nil and taskCfg.f_Award ~= nil and taskCfg.f_Award ~= "" then
        local reward = decodeJsonStrToTabel(taskCfg.f_Award)[1];
        if reward ~= nil then
            itemModelId = reward[1];
        end
    end
    if itemModelId ~= nil then
        UIComponentInterface:SetItemAllById(self.btnChapterRewardIcon, nil, nil, itemModelId);
    else
        self.btnChapterRewardIcon.url = "";
    end
end

function UIBattleTeamEditor:GetHeroID()
    local Count = 0;
    for _, v in ipairs(self.tabHeroPosData) do
        if not v["partnerModelId"] then
            break ;
        else
            Count = Count + 1;
        end
    end
    return self.tabHeroPosData[math.random(1, Count)]
end

function UIBattleTeamEditor:GetHeroType(modelId)
    local heroCfg = dataTable.getRow("t_hero", modelId)
    if heroCfg then
        return heroCfg["f_HeroType"]
    end
    return nil
end

function UIBattleTeamEditor:initEnemyFormation()
    if self.otherSupSkill then
        local skillDataOther = G.dataTable["t_skillshow"][tostring(self.otherSupSkill)];
        if skillDataOther then
            self.supSkillRight:GetChild("icon"):GetChild("icon").url = "ui://SkillAtlas/" .. skillDataOther.f_SkillIcon
        end
    end
    local monsters = self.oppoFormations[self.formationsIndex]
    if monsters == nil or #monsters <= 0 then
        monsters = {}
        for i = 1, nodeCount do
            local item = {}
            item["partnerId"] = nil
            item["partnerModelId"] = nil
            table.insert(monsters, item)
        end
        self.enemyHelpManId[self.formationsIndex] = nil
        self.enemyHelpMan[self.formationsIndex] = { partnerModelId = nil, partnerId = nil }
    end
    self.tabMonsterPosData = {}
    if type(self.powerEnemyNum) == "table" then
        self.powerEnemy.text = getNumString(self.powerEnemyNum[self.formationsIndex])
    else
        self.powerEnemy.text = getNumString(self.powerEnemyNum)
    end

    for i = 1, nodeCount do
        local v = monsters[i]
        if i <= nodeCount then
            local info = {
                partnerModelId = "0",
                level = 1,
                icon = "",
                state = nil,
                teamIndex = 2,
                weaponLevel = nil,
                weaponRank = 1,
                site = i
            }
            if v ~= nil then
                info = {
                    partnerId = v["partnerId"],
                    partnerModelId = v["partnerModelId"],
                    level = v["level"] or 1,
                    star = v["star"],
                    type = self:GetHeroType(v["partnerModelId"]),
                    weaponLevel = v["weaponLevel"],
                    weaponRank = v["weaponRank"],
                    icon = "",
                    state = nil,
                    teamIndex = 2,
                    site = i,
                    skinId = v["skinId"]
                }
            end
            table.insert(self.tabMonsterPosData, info)
        end

    end
    if #self.tabMonsterPosData < nodeCount then
        for i = #self.tabMonsterPosData + 1, nodeCount do
            local info = {
                partnerModelId = "0",
                level = 1,
                icon = "",
                state = nil,
                teamIndex = 2,
                site = i
            }
            table.insert(self.tabMonsterPosData, info)

        end
    end
    local HelpInfo = {
        partnerModelId = "0",
        level = 1,
        icon = "",
        state = nil,
        teamIndex = 2,
        site = SUPPORT_TEAMMATE_SITE
    }
    if self.enemyHelpMan[self.formationsIndex] and self.enemyHelpManId[self.formationsIndex] ~= 0 then
        HelpInfo = {
            partnerId = self.enemyHelpMan[self.formationsIndex]["partnerId"],
            partnerModelId = self.enemyHelpMan[self.formationsIndex]["partnerModelId"],
            level = self.enemyHelpMan[self.formationsIndex]["level"] or 1,
            star = self.enemyHelpMan[self.formationsIndex]["star"],
            type = self:GetHeroType(self.enemyHelpMan[self.formationsIndex]["partnerModelId"]),
            icon = "",
            state = nil,
            teamIndex = 2,
            site = SUPPORT_TEAMMATE_SITE
        }
    end
    self.tabMonsterPosData[nodeCount + 1] = HelpInfo
    for i = 1, #self.tabMonsterPosData do
        local itemData = self.tabMonsterPosData[i]
        if itemData.partnerId ~= nil then
            self.rightBottoms[i].visible = true;
            local bIndex = Config.IconQualityBottom[logicMgr.HeroManager.starToQuality(itemData.star)]
            self.rightBottoms[i].url = "ui://ICONAtlas/" .. bIndex
        else
            self.rightBottoms[i].visible = false
        end
        local role = self.rightPos[itemData.site]
        --[[if self.ctrlIfMainBattle.selectedIndex == 5 and i==3 then
            role.parent:SetChildIndex(role,108)
        end--]]
        local type = self.isShowTitle and 1 or 0
        local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem)
        if ctrlItem ~= nil then
            --初始人物信息
            role.visible = true
            --logicMgr.UIShowManager.getTeamHeroItem(itemData.teamIndex, i, self.titleNode)
            ctrlItem.initData(role, itemData, i, type, function(data)
                UIBattleTeamEditor:showHeroEffect(data)
            end, fightType, nil, nodeCount + 1, self.formationType)
        end
    end
    if self.ctrlIfMainBattle.selectedIndex ~= 5 then
        --self.titleNode:GetChild("title27").visible = false
        --self.titleNode:GetChild("title28").visible = false
    end
end

function UIBattleTeamEditor:showHeroEffect(data)
    --[[if self.isInit then return end
    local ani = self.showHeroEffects[data.teamId][data.idx]
    ani.visible = true
    ani.spineAnimation.state:SetAnimation(0, "idle", false)
    local idleAniTime = ani.spineAnimation.state.Data.SkeletonData:FindAnimation("idle").Duration
    utimer.remove(self.effectTimers[data.teamId .. data.idx])
    local timer = utimer.timeCall(self.showEffectEnd, idleAniTime * 1000, 1)
    self.effectTimers[data.teamId .. data.idx] = timer
    table.insert(self.effectList, ani)--]]
end

function UIBattleTeamEditor.showEffectEnd()
    local self = UIBattleTeamEditor;
    local endEffect = table.remove(self.effectList, 1)
    if endEffect and endEffect.visible then
        endEffect.visible = false
    end
end

function UIBattleTeamEditor:RemoveEffect()
    self.effectList = {};
    for i, v in pairs(self.effectTimers) do
        utimer.remove(v)
    end
end

function UIBattleTeamEditor:initFormation()
    local tempDta = clone(self.tabHeroPosData)
    for i = 1, self.formationsMax do
        self.tabHeroPosDataTemp[i] = {}
        for j = 1, nodeCount do
            self.tabHeroPosDataTemp[i][j] = {}
        end
    end
    for j = 1, #self.formations do
        for i = 1, nodeCount do
            self.tabHeroPosDataTemp[j][i] = {}
        end
    end
    for j = 1, #self.formations do
        local tempFormation = self.formations[j]
        if tempFormation ~= nil and table.getn(tempFormation) > 0 then
            for i = 1, nodeCount do
                --- 根据已保存的阵容恢复位置信息
                local partnerId = tempFormation[i]
                if partnerId ~= nil then
                    for k = 1, #self.tableHeros do
                        if tostring(partnerId) == tostring(self.tableHeros[k].partnerId) then
                            self.tabHeroPosDataTemp[j][i]["partnerId"] = self.tableHeros[k]["partnerId"]
                            self.tabHeroPosDataTemp[j][i]["partnerModelId"] = self.tableHeros[k]["partnerModelId"]
                            self.tabHeroPosDataTemp[j][i]["level"] = self.tableHeros[k]["level"]
                            self.tabHeroPosDataTemp[j][i]["star"] = self.tableHeros[k]["star"]
                            self.tabHeroPosDataTemp[j][i]["weaponLevel"] = self.tableHeros[k]["weaponLevel"]
                            self.tabHeroPosDataTemp[j][i]["icon"] = ""
                            self.tabHeroPosDataTemp[j][i]["type"] = self.tableHeros[k]["type"]
                            self.tabHeroPosDataTemp[j][i]["state"] = self.tableHeros[k]["state"]
                            self.tabHeroPosDataTemp[j][i]["power"] = self.tableHeros[k]["power"]
                            self.tabHeroPosDataTemp[j][i]["realPower"] = self.tableHeros[k]["realPower"]
                            self.tabHeroPosDataTemp[j][i]["site"] = i
                            self.tabHeroPosDataTemp[j][i]["weaponRank"] = logicMgr.HeroManager.GetWeaponQuality(self.tableHeros[k]["partnerModelId"])
                        end
                    end
                end
            end
        end
        if tonumber(self.helpManId[j]) ~= 0 then
            if not (self.playerIds and self.playerIds[6] and tonumber(tostring(self.playerIds[6])) ~= 0) then
                for k = 1, #self.tableHeros do
                    if tostring(self.helpManId[j]) == tostring(self.tableHeros[k].partnerId) then
                        self.helpMan[j]["partnerId"] = self.tableHeros[k]["partnerId"]
                        self.helpMan[j]["partnerModelId"] = self.tableHeros[k]["partnerModelId"]
                        self.helpMan[j]["level"] = self.tableHeros[k]["level"]
                        self.helpMan[j]["star"] = self.tableHeros[k]["star"]
                        self.helpMan[j]["weaponLevel"] = self.tableHeros[k]["weaponLevel"]
                        self.helpMan[j]["icon"] = ""
                        self.helpMan[j]["type"] = self.tableHeros[k]["type"]
                        self.helpMan[j]["state"] = self.tableHeros[k]["state"]
                        self.helpMan[j]["power"] = self.tableHeros[k]["power"]
                        self.helpMan[j]["realPower"] = self.tableHeros[k]["realPower"]
                        self.helpMan[j]["site"] = SUPPORT_TEAMMATE_SITE
                        self.helpMan[j]["weaponRank"] = logicMgr.HeroManager.GetWeaponQuality(self.tableHeros[k]["partnerModelId"])
                    end
                end
            else
                if self.isFriendBattle then
                    if self.helpMan[j]["partnerId"] and int64ToNumber(self.helpMan[j]["partnerId"]) ~= 0 then
                        self.helpMan[j] = self.helpMan[j]
                    else
                        local config = logicMgr.FriendBattleManager.GetHerobyIndex(6, self.formationType)
                        if config then
                            self.helpMan[j]["partnerId"] = config["partnerId"]
                            self.helpMan[j]["partnerModelId"] = config["partnerModelId"]
                            self.helpMan[j]["level"] = config["level"]
                            self.helpMan[j]["star"] = config["star"]
                            self.helpMan[j]["weaponLevel"] = config["weaponLevel"]
                            self.helpMan[j]["type"] = config["type"]
                            self.helpMan[j]["power"] = config["power"]
                            self.helpMan[j]["realPower"] = 0
                            self.helpMan[j]["name"] = config["name"]
                            self.helpMan[j]["icon"] = ""
                            self.helpMan[j]["site"] = SUPPORT_TEAMMATE_SITE
                            self.helpMan[j]["weaponRank"] = logicMgr.HeroManager.GetWeaponQuality(config["partnerModelId"])
                        end
                    end
                end
            end
        else
            self.helpMan[j] = {}
        end
    end

    self.tabHeroPosData = self.tabHeroPosDataTemp[self.formationsIndex]
    tempDta = nil
    if self.isFriendBattle then
        logicMgr.FriendBattleManager.BattleTeam(self.tabHeroPosData, self.helpMan[self.formationsIndex])
    end
end

function UIBattleTeamEditor:refreshPower()
    local powerNum = 0;
    if fightType == EnumConst.FightTypeConst.ARENA and param ~= nil and param.arena_type == EnumConst.ArenaBattleType.TeamCross then
        for k = 1, #self.tabHeroPosData do
            local localPartnerId = self.tabHeroPosData[k]["partnerId"];
            if localPartnerId ~= nil and tostring(localPartnerId) ~= "0" then
                powerNum = powerNum + logicMgr.HeroManager.CalcHeroPowerWithLv(localPartnerId, 300);
            end
        end
    else
        for i = 1, #self.tabHeroPosData do
            if self.tabHeroPosData[i]["power"] ~= nil then
                powerNum = powerNum + self.tabHeroPosData[i]["power"];
            end
        end
    end

    if self.helpMan then
        if not self.isFriendBattle then
            local hero = logicMgr.HeroManager.getHeroDatabyPartnerId(self.helpMan[self.formationsIndex].partnerId)
            if hero then
                powerNum = powerNum + hero.power
            end
        end
    end

    self.power.text = getNumString(powerNum)
end

--模型显示
function UIBattleTeamEditor:rendererFormation()
    self:refreshPower();
    for i = 1, #self.tabHeroPosData do
        if nodeCount >= i then
            local role = self.leftRole[i]
            --[[if self.ctrlIfMainBattle.selectedIndex == 5 and i==3 then
                role.parent:SetChildIndex(role,91)
            end--]]
            local pos = self.leftRect[i]
            if role.dragBounds == nil or role.dragBounds.y ~= self.leftGroup.y then
                role.dragBounds = UnityEngine.Rect.New(self.leftGroup.x, self.leftGroup.y, self.leftGroup.actualWidth, self.leftGroup.actualHeight);
            end
            role.draggable = true
            role:SetPosition(pos.x, pos.y, 0)

            local itemData = self.tabHeroPosData[i]
            if itemData.partnerId ~= nil then
                self.leftBottoms[i].visible = true
                local bIndex = nil
                if self.formationType == EnumConst.FightTypeConst.RankBattle then
                    bIndex = Config.IconQualityBottom[15]
                else
                    bIndex = Config.IconQualityBottom[Mathf.Floor(itemData.star / 10)]
                end
                self.leftBottoms[i].url = "ui://ICONAtlas/" .. bIndex
            else
                self.leftBottoms[i].visible = false
            end
            local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem)
            local type = self.isShowTitle and 1 or 0
            if ctrlItem ~= nil then
                --初始装备信息
                --logicMgr.UIShowManager.getTeamHeroItem(itemData.teamIndex, i, self.titleNode)
                ctrlItem.initData(role, itemData, i, type, function(data)
                    UIBattleTeamEditor:showHeroEffect(data)
                end, fightType, self.isShowDebris, nodeCount + 1, self.formationType)
            end
            if self.tabHeroPosData[i].partnerId == nil then
                role.draggable = false
            else
                role.draggable = true
            end
        end
    end

    local role = self.leftRole[nodeCount + 1]
    local pos = self.leftRect[nodeCount + 1]
    if role.dragBounds == nil or role.dragBounds.y ~= self.leftGroup.y then
        role.dragBounds = UnityEngine.Rect.New(self.leftGroup.x, self.leftGroup.y, self.leftGroup.actualWidth, self.leftGroup.actualHeight);
    end
    role.draggable = true
    role:SetPosition(pos.x, pos.y, 0)
    local itemData = self.helpMan[self.formationsIndex]
    if itemData.partnerId ~= nil then
        self.leftBottoms[nodeCount + 1].visible = true;
        local bIndex = nil
        if self.formationType == EnumConst.FightTypeConst.RankBattle then
            bIndex = Config.IconQualityBottom[15];
        else
            bIndex = Config.IconQualityBottom[Mathf.Floor(itemData.star / 10)]
        end
        self.leftBottoms[nodeCount + 1].url = "ui://ICONAtlas/" .. bIndex
    else
        self.leftBottoms[nodeCount + 1].visible = false
    end
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.TeamHeroItem)
    local type = self.isShowTitle and 1 or 0

    if ctrlItem ~= nil then
        --初始装备信息
        --logicMgr.UIShowManager.getTeamHeroItem(itemData.teamIndex, nodeCount + 1, self.titleNode)
        ctrlItem.initData(role, itemData, nodeCount + 1, type, function(data)
            UIBattleTeamEditor:showHeroEffect(data)
        end, fightType, self.isShowDebris, nodeCount + 1, self.formationType)
    end
    if self.ctrlIfMainBattle.selectedIndex ~= 5 then
        --self.titleNode:GetChild("title17").visible = false
        --self.titleNode:GetChild("title18").visible = false
    end
    if self.helpMan[self.formationsIndex].partnerId == nil then
        role.draggable = false
    else
        role.draggable = true
    end
end

function UIBattleTeamEditor:onClickItemIndex(index)

    self.formationsIndex = index
    if self.formationsIndex < 1 then
        self.formationsIndex = 1
    end
    if self.formationsIndex > self.formationsMax then
        self.formationsIndex = self.formationsMax
    end
    for i = 1, self.formationsMax do
        if self.formations[i] ~= nil and self.helpManId[i] ~= 0 then
            self.formations[i][nodeCount + 1] = self.helpManId[i]
        end
    end
    self.clearController:SetSelectedIndex(0)
    if fightType == EnumConst.FightTypeConst.DUNGEON then
        local data = logicMgr.BattlePlaybackManager.GetGroupBossHistory(self.formationsIndex);
        if data and data.record and data.record.win == 1 then
            self.clearController:SetSelectedIndex(1)
        end
    elseif fightType == EnumConst.FightTypeConst.GuildBattlePlus then
        if param.formationIsOver and param.formationIsOver[self.formationsIndex] then
            self.clearController:SetSelectedIndex(1)
        end
    end
    self:initFormation()
    self:rendererFormation()
    self:initEnemyFormation()
    self:onClickType()
    self:RefreshBossBtn()
end

function UIBattleTeamEditor:createFormation()
    local formation = {}
    if #self.formations > 1 then
        for j = 1, #self.formations do
            for i = 1, #self.tabHeroPosDataTemp[j] do
                if formation[j] == nil then
                    formation[j] = {}
                end
                if self.tabHeroPosDataTemp[j][i]["partnerId"] ~= nil and tonumber(self.tabHeroPosDataTemp[j][i]["partnerId"]) > 0 then
                    table.insert(formation[j], self.tabHeroPosDataTemp[j][i]["partnerId"])
                else
                    table.insert(formation[j], "0")
                end
            end
        end
    end
    return formation
end

-- 英雄是否在阵容中（是否检查当前设置的阵容）
function UIBattleTeamEditor:isInFormations(partnerId, checkCurFormation)
    for i = 1, #self.formations do
        if i ~= self.formationsIndex or checkCurFormation then
            for k = 1, #self.formations[i] do
                if self.formations[i][k] == partnerId then
                    return true
                end
            end
        end
    end
    return false
end

function UIBattleTeamEditor:refreshFormation()
    local self = UIBattleTeamEditor
    local formation = logicMgr.FormationManager.GetFormation(EnumConst.FormationType.Duplicate)
    self.formations[self.formationsIndex] = {}
    if formation ~= nil then
        for k, v in pairs(formation) do
            if k == nodeCount + 1 then
                self.helpManId[self.formationsIndex] = tostring(v)
            else
                self.formations[self.formationsIndex][k] = tostring(v)
            end
            local state = EnumConst.HeroHeadStateEnum.BATTLE
            for i = 1, #self.tableHeros do
                if tostring(self.helpManId[self.formationsIndex]) == tostring(self.tableHeros[i].partnerId) then
                    --local data = logicMgr.HeroManager.setHeroState(self.tableHeros[i].partnerId, true, state, self.formationType, self.tableHeros[i])
                    self.tableHeros[i]["state"] = 4
                end
                if self.tableHeros[i].partnerId == tostring(v) then
                    --local data = logicMgr.HeroManager.setHeroState(self.tableHeros[i].partnerId, true, state, self.formationType, self.tableHeros[i])
                    self.tableHeros[i]["state"] = 4
                end
            end
        end
    end

    self:onClickType(true, self.curTabType)
    self:initFormation()
    self:rendererFormation()
    self:initEnemyFormation()
end

function UIBattleTeamEditor:TouchAnyKeyMsg()
end

--引导移动
function UIBattleTeamEditor:GuideTeamRoleTouch(name, index, _end)
    local role = self.leftRole[index]
    if not role then
        return
    end
    if name == "begin" then
        role:StartDrag()
    elseif name == "end" then
        role:StopDrag()
        if isIntersect(self.leftRect[_end], role) then
            FireEvent(Config.EventType.GuideTeamRoleTouchSuc)
        else
            _end = index
        end
        self:changePosByIndex(index, _end)
        role:SetPosition(self.leftRect[index].x, self.leftRect[index].y, 0)
        if (index ~= 0) then
            role.parent:SetChildIndex(role, self.leftIndex[index])
        end
    end
end

--引导查找heroId
function UIBattleTeamEditor:GuideFindHeroIdMsg(heroId)
    if self.tabOwner == nil or #self.tabOwner == 0 then
        return
    end

    local sortFunc = HeroManager.getSortHeroByType()
    table.sort(self.tabOwner, function(a, b)
        local aw = a.partnerModelId == heroId and 10 or 0
        local bw = b.partnerModelId == heroId and 10 or 0
        if aw ~= bw then
            return aw > bw
        end
        return sortFunc(a, b)
    end)
    self.dynamicList.numItems = #self.tabOwner
    self.dynamicList:ScrollToView(0)
    for k, v in pairs(self.tabOwner) do
        if v.partnerModelId == tostring(heroId) then
            local item = self.dynamicList:GetChildAt(k - 1)
            FireEvent(Config.EventType.GuideFindHeroIdSuc, item)
            return
        end
    end
    logError("[引导]找不到节点,heroId  " .. heroId)
end

--职业爬塔限定能够选到的英雄类型（英雄类型按钮置灰）
function UIBattleTeamEditor:AdvancedTowerDisableBtn()
    for k, v in pairs(self.occupationBtns) do
        v.grayed = true
    end
    local canSelectHeroTypes = logicMgr.TowerManager.getAdvancedTowerHeroType()
    for k, v in pairs(canSelectHeroTypes) do
        for m, n in pairs(self.occupationBtns) do
            local occupationType = tonumber(string.split(n.name, "_")[2]) or 0
            if occupationType == v then
                n.grayed = false
            end
        end
    end
end

--激活英雄职业类型按钮
function UIBattleTeamEditor:EnableHeroTypeBtn()
    for k, v in pairs(self.occupationBtns) do
        v.grayed = false
    end
end

--刷新羁绊技能
function UIBattleTeamEditor:refreshCombinationSkill()
    local formationList = {};
    local enemyFormationList = {};
    for i, v in pairs(self.tabHeroPosData) do
        if v and v.partnerModelId and tonumber(v.partnerModelId) ~= 0 then
            local modelId = v.partnerModelId;
            table.insert(formationList, modelId)
        end
    end
    local modelId = self.helpMan[self.formationsIndex].partnerModelId;
    if modelId and tonumber(modelId) ~= 0 then
        table.insert(formationList, modelId)
    end
    if self.oppoFormations[self.formationsIndex] then
        for i, v in pairs(self.oppoFormations[self.formationsIndex]) do
            if v and v.partnerModelId and tonumber(v.partnerModelId) ~= 0 then
                local modelEnemyId = v.partnerModelId;
                table.insert(enemyFormationList, modelEnemyId)
            end
        end
        local modelEnemyId = self.enemyHelpMan[self.formationsIndex].partnerModelId;
        if modelEnemyId and tonumber(modelEnemyId) ~= 0 then
            table.insert(enemyFormationList, modelEnemyId)
        end
    end

    self.combinationListInfo = HeroManager.getCombinationSkillList(formationList);
    self.combinationListInfoEnemy = HeroManager.getCombinationSkillList(enemyFormationList);
    self.combinationListBgCtrl.selectedIndex = table.getn(self.combinationListInfo) > 0 and 1 or 0;

    local isPvE = FightManager.checkIsFightTypePVE(fightType);
    if not isPvE then
        self.combinationListEnemy.visible = true;
        self.combinationListEnemyBgCtrl.selectedIndex = table.getn(self.combinationListInfoEnemy) > 0 and 1 or 0;
        self.combinationListEnemy.numItems = table.getn(self.combinationListInfoEnemy);
    else
        self.combinationListEnemy.visible = false;
        self.combinationListEnemyBgCtrl.selectedIndex = 0;
    end
    self.combinationList.numItems = table.getn(self.combinationListInfo);

end

function UIBattleTeamEditor:rendererCombinationSkillItem(idx, obj, listInfo, type)
    local data = listInfo[idx + 1];
    local cfg = HeroManager.getCombinationInfo();
    local nameText = obj:GetChild("title");
    local iconImg = obj:GetChild("icon");
    local typeCtrl = obj:GetController("type");
    iconImg.url = "ui://SkillAtlas/" .. cfg[tostring(data.skillId)].f_CombinationIcon;
    nameText.text = getLanguage(cfg[tostring(data.skillId)].f_CombinationName);
    typeCtrl.selectedIndex = type;
    obj.onClick:Clear();
    obj.onClick:Add(function()
        self.combinationComCtrl.selectedIndex = 1;
        self:onShowComb(data);
    end)
end

function UIBattleTeamEditor:onShowComb(heroData)
    local heroList = self.combinationCom:GetChild("hero");
    heroList.itemRenderer = function(idx, obj)
        self:rendererHero(idx + 1, obj, heroData);
    end
    local cfg = HeroManager.getCombinationInfo()[tostring(heroData.skillId)];
    heroList.numItems = table.getn(heroData.heroIds);
    local desText = self.combinationCom:GetChild("Describe");
    desText.text = getLanguage(heroData.decs);

    local skillNameText = self.combinationCom:GetChild("title");
    skillNameText.text = getLanguage(cfg.f_CombinationName);

    local iconImg = self.combinationCom:GetChild("icon");
    iconImg.url = "ui://SkillAtlas/" .. cfg.f_CombinationIcon;

end

function UIBattleTeamEditor:rendererHero(idx, obj, info)
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    --local ctrl = itemobj:GetTransition("Effect_List")
    --ctrl:Play()
    local hero = info.heroIds[idx];
    if charactor ~= nil then
        --初始英雄信息
        local heroData = {};
        logicMgr.HeroManager.copyHeroConfigbyModelId(hero, heroData);

        if heroData then
            charactor.initData(obj, heroData, nil, nil, nil, nil, nil, nil, true);
        end
    end
end

function UIBattleTeamEditor.GetMapName()
    if mapName ~= nil and mapName ~= "" then
        return "Prefabs/MapPref/" .. mapName
    end

    return nil
end

function UIBattleTeamEditor:SetBgType()
    mapName = logicMgr.MapManager.GetMapNameByFightType(fightType)
    if mapName == nil then
        return
    end
    local mapPos = decodeJsonStrToTabel(G.dataTable["t_mappos"][mapName]["f_MapPos"]) or {};
    resMgr:LoadMapPrefab("Prefabs/MapPref/" .. mapName, function(obj)
        if self.goWrapper == nil then
            self.goWrapper = GoWrapper.New();
        end
        if self.mapObj ~= nil then
            destroyImmediate(self.mapObj);
        end
        self.mapObj = newObject(obj)
        self.mapObj:SetActive(true)
        local battleMap = self.mapObj.transform:Find("BattleMap")
        self.goWrapper:SetWrapTarget(self.mapObj, false)
        self.mapHolder:SetNativeObject(self.goWrapper)
        Util.Lua_SetLocalPositionXYZ(battleMap, mapPos[1], mapPos[2], mapPos[3]);
        Util.Lua_SetLocalScaleXYZ(battleMap, 130, 130, 130);
        Util.Lua_SetLocalRotationXYZ(battleMap, -40, 0, 0);
    end)
end

return UIBattleTeamEditor